• No results found

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

N/A
N/A
Protected

Academic year: 2021

Share "CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O"

Copied!
27
0
0

Loading.... (view fulltext now)

Full text

(1)

1

CSE 1223: Introduction to

Computer Programming in Java

Chapter 7 – File I/O

(2)

Sending Output to a (Text) File

import java.util.Scanner;

import java.io.*;

public class TextFileOutputDemo1 {

public static void main(String[] args) throws IOException {

Scanner in = new Scanner(System.in);

System.out.print(“Enter your name: ”);

String name = in.nextLine();

PrintWriter outputFile = new PrintWriter(“out.txt”);

outputFile.println(name);

outputFile.close();

} }

(3)

Creating a File for Text Output

We need a new class:

PrintWriter

To gain access to it we need to import it with:

import java.io.*;

To create and open the file:

PrintWriter outFile =

new PrintWriter(fileName);

3

(4)

Creating a File for Text Output

We need a new class:

PrintWriter

To gain access to it we need to import it with:

import java.io.*;

To create and open the file:

PrintWriter outFile =

new PrintWriter(fileName);

String

(5)

Writing Output to a Text File

The PrintWriter class has output methods you are already familiar with:

print

println

Instead of calling System.out.print(...) or System.out.println(...), you invoke:

outFile.print(...)

outFile.println(...)

5

(6)

Writing Output to a Text File

The PrintWriter class has output methods you are already familiar with:

print

println

Instead of calling System.out.print(...) or System.out.println(...), you invoke:

outFile.print(...)

outFile.println(...) PrintWriter object

(7)

Closing the File

It is important to remember to explicitly close a file you are done writing to:

outFile.close()

7

(8)

Closing the File

It is important to remember to explicitly close a file you are done writing to:

outFile.close()

PrintWriter object

(9)

Your Turn

Write a program that asks the user for a file name and then outputs the numbers 1

through 10, one per line, to the corresponding file.

9

(10)

Output Numbers

import java.util.Scanner;

import java.io.*;

public class OutputNumbers {

public static void main(String[] args) throws IOException {

Scanner in = new Scanner(System.in);

System.out.print(“Enter the file name: ”);

String fileName = in.nextLine();

PrintWriter outputFile = new PrintWriter(fileName);

for (int i = 1; i <= 10; i++) {

outputFile.println(i);

}

outputFile.close();

} }

(11)

What If an Error Occurs?

What could go wrong when we try to create a file?

We might not be able to create it!

In that case an exception (error) is generated/raised by the program.

What can we do about it?

11

(12)

Exceptions

There are a variety of errors that can occur in a Java program that result in an exception

being raised

Java forces us to deal with some of them by

either explicitly stating that such an exception might occur in our program

or by catching the exception and dealing with it in our code

(13)

Stating That Exception Might Occur

import java.util.Scanner;

import java.io.*;

public class TextFileOutputDemo1 {

public static void main(String[] args) throws IOException {

Scanner in = new Scanner(System.in);

System.out.print(“Enter your name: ”);

String name = in.nextLine();

PrintWriter outputFile = new PrintWriter(“out.txt”);

outputFile.println(name);

outputFile.close();

} }

13

(14)

Dealing With Exception If It Occurs

import java.util.Scanner;

import java.io.*;

public class TextFileOutputDemo2 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print(“Enter your name: ”);

String name = in.nextLine();

try {

PrintWriter outputFile = new PrintWriter(“out.txt”);

outputFile.println(name);

outputFile.close();

} catch (IOException e) {

System.out.println(“Error opening the file out.txt”);

} } }

(15)

Try-Catch

You can think of it as a control structure in that it affects the flow of execution of the program

when an exception occurs.

try {

// statements possibly raising exception }

catch (exception declaration) {

// statements dealing with exception }

15

(16)

Reading Input from a (Text) File

import java.util.Scanner;

import java.io.*;

public class TextFileInputDemo1 {

public static void main(String[] args) throws IOException

{

File file = new File("in.txt");

Scanner inputFile = new Scanner(file);

String line = inputFile.nextLine();

inputFile.close();

System.out.println(line);

}

(17)

Opening a File for Text Input

We need a new class:

File

To gain access to it we need to import it with:

import java.io.*;

To open an existing file:

File file = new File(fileName);

Scanner inFile = new Scanner(file);

17

(18)

Opening a File for Text Input

We need a new class:

File

To gain access to it we need to import it with:

import java.io.*;

To open an existing file:

File file = new File(fileName);

Scanner inFile = new Scanner(file);

String

(19)

Reading Input from a Text File

The Scanner class has input methods you are already familiar with:

nextLine, nextInt, nextDouble, etc.

Now we also need a way to check when we reach the end of the file:

boolean hasNext()

It takes no parameters and returns true if there is more data to read, and false otherwise

19

(20)

Closing the File

It is important to remember to explicitly close a file you are done reading from:

inFile.close()

(21)

Closing the File

It is important to remember to explicitly close a file you are done reading from:

inFile.close()

21

Scanner object

(22)

Your Turn

Complete the following program that asks the user for a file name, opens the file, reads one line at a time and outputs the line to the

screen, until it reaches the end of the file.

Make sure you catch the possible

IOException in a try-catch statement.

(23)

Read File

import java.util.Scanner;

import java.io.*;

public class ReadFile {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print("Enter file name: ");

String fileName = in.nextLine();

try {

File file = new File(fileName);

Scanner inputFile = new Scanner(file);

while (inputFile.hasNext()) {

String line = inputFile.nextLine();

System.out.println(line);

}

inputFile.close();

} catch (IOException e) { System.out.println(

"There was a problem reading from " + fileName);

} } }

23

(24)

Reading Non-String Values

Method readLine reads a line of input and returns it as a String

What if we want to input integer or real values?

We read them as strings with readLine, and then convert the string value to the

corresponding numeric value

(25)

Converting String Values

There are useful methods to handle the conversion of a String value to the

corresponding numeric value:

int Integer.parseInt(String str)

double Double.parseDouble(String str)

For example:

int i = Integer.parseInt(“1234”);

double d = Double.parseDouble(“3.1415”);

25

(26)

Your Turn

Write a program that asks the user for a file name, opens the file, reads a bunch of

integer values, one per line, until it reaches the end of the file. The program computes

and outputs the average of the integers to the screen.

Make sure you catch the possible

IOException in a try-catch statement.

(27)

Your Turn

27

References

Related documents

See, e.g., In re Sage Realty Corp., 91 N.Y.2d 30, 35 (NY 1997) (“We conclude that the majority position, as adopted in the final draft of the American Law Institute Restatement

The positive and signi…cant coe¢ cient on the post shipment dummy in the fourth column implies that prices charged in post shipment term transactions are higher than those charged

Marketing Campaign Detail tab has the following sections: Basic Information, Remarks, Default Handling Options, Activity Reason, Leads Distribution Parameters and Conditional Handling

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

(B) the adsorption at a single site on the surface may involve multiple molecules at the same time.. (C) the mass of gas striking a given area of surface is proportional to the

The key segments in the mattress industry in India are; Natural latex foam, Memory foam, PU foam, Inner spring and Rubberized coir.. Natural Latex mattresses are

93 / 42 / EEC Medical devices, class IIb (European Directive for Medical Devices), 97/ 23 / EC (Pressure Equipment Directive), 2006 / 42 / EC (Machinery Directive) ; EN 13060

• Speed of weaning: induction requires care, but is relatively quick; subsequent taper is slow • Monitoring: Urinary drug screen, pain behaviors, drug use and seeking,