Files from Ch 4 File Input and Output

  • Slides: 21
Download presentation
Files from Ch 4

Files from Ch 4

File Input and Output o o Reentering data all the time could get tedious

File Input and Output o o Reentering data all the time could get tedious for the user. The data can be saved to a file. n o Files: n n n o Files can be input files or output files. Files have to be opened. Data is then written to the file. The file must be closed prior to program termination. In general, there are two types of files: n n binary text

Writing Data To a File o Objects from the following classes are used to

Writing Data To a File o Objects from the following classes are used to write data to files: n n n File. Writer – This class allows basic file writing functionality. Print. Writer – This class allows the programmer to write files using the same style that is used to write to the screen (i. e. print and println).

The File. Writer Class o The File. Writer clas provides other classes with the

The File. Writer Class o The File. Writer clas provides other classes with the basic file writing functionality. System. out. println(“Enter the filename. ”); filename = Keyboard. read. String(); File. Writer fwriter = new File. Writer(filename); o o This will create an object that can access the filename. Warning: if the file already exists, it will be erased and replaced with the new file.

The Print. Writer Class o o o The Print. Writer class adds to the

The Print. Writer Class o o o The Print. Writer class adds to the functionality of the File. Writer class. The Print. Writer cannot directly access the file but must work through the File. Writer class. The Print. Writer needs a File. Writer object in order to work: File. Writer fwriter = new File. Writer("Student. Data. txt"); Print. Writer output. File = new Print. Writer(fwriter);

The Print. Writer Class o Once linked to the fwriter object, the output. File

The Print. Writer Class o Once linked to the fwriter object, the output. File object can talk to the file. output. File. open(); output. File. println(“Jim”); output. File. close(); o o Just as with the System. out object, the println method of the Print. Writer class will place a newline character after the written data. The print method can be used to avoid writing the newline character.

Exceptions o o When something unexpected happens in a Java program, an exception is

Exceptions o o When something unexpected happens in a Java program, an exception is thrown. The method currently executing when the exception is thrown must either handle the exception or pass it up the line. Handling the exception will be discussed later. To pass it up the line, the method needs a throws clause in the method header.

Exceptions o o To insert a throws clause in a method header, simply add

Exceptions o o To insert a throws clause in a method header, simply add the word throws and the name of the expected exception. The class Exception can be used to catch all exceptions. public static void main(String[] args) throws IOException{…} o o o File I/O is a checked exception (meaning the exception must be handled or passed up). A program with file I/O will generate a compile-time error if the exception is not handled or passed up. Example:

File. Write. Demo. java o o o o o import java. util. Scanner; //

File. Write. Demo. java o o o o o import java. util. Scanner; // Needed for Scanner class import java. io. *; // Needed for file classes public class File. Write. Demo { public static void main(String[] args) throws IOException { String filename; // File name String friend. Name; // Friend's name int num. Friends; // Number of friends Scanner keyboard = new Scanner(System. in); o o System. out. print("How many friends do you have? "); num. Friends = keyboard. next. Int(); keyboard. next. Line(); o o o System. out. print("Enter the filename: "); filename = keyboard. next. Line();

File. Write. Demo. java o o o o } } File. Writer fwriter =

File. Write. Demo. java o o o o } } File. Writer fwriter = new File. Writer(filename); Print. Writer output. File = new Print. Writer(fwriter); for (int i = 1; i <= num. Friends; i++) { // Get the name of a friend. System. out. print("Enter the name of friend " + "number " + i + ": "); friend. Name = keyboard. next. Line(); output. File. println(friend. Name); } output. File. close(); System. out. println("Data written to the file. ");

Appending Text to a File o To avoid erasing a file that already exists:

Appending Text to a File o To avoid erasing a file that already exists: n Create a File. Writer object using an optional boolean argument that tells the object to append data to the file. File. Writer fwriter = new File. Writer(“filename”, true); o Data written to a file created in such a manner will be appended to the end of the current file.

Specifying a File Location Windows’ Crazy Backslash o o o Windows evolved from DOS.

Specifying a File Location Windows’ Crazy Backslash o o o Windows evolved from DOS. Since DOS was simply a hacked version of CP/M, it maintained the backslash () as a directory separator. Remember, if the backslash is used in a String literal, it is the escape character so there must be two of them. File. Writer fwriter = new File. Writer("A: \Price. List. txt"); Print. Writer output. File = new Print. Writer(fwriter);

Specifying a File Location o o o This is only necessary if the backslash

Specifying a File Location o o o This is only necessary if the backslash is in a String literal. If the backslash is in a String object then it will be handled properly. Fortunately, Java allows Unix style filenames using the forward slash (/) to separate directories. File. Writer fwriter = new File. Writer("/home/rharrison/names. txt"); Print. Writer output. File = new Print. Writer(fwriter);

Reading Data From a File o Java provides several classes to read data from

Reading Data From a File o Java provides several classes to read data from a file. n File. Reader o n Open an existing file for reading and establish a connection with it. Buffered. Reader o Uses a buffer to allow the reading of full lines of text at a time rather than one byte at a time.

The File. Reader and Buffered. Reader Classes System. out. print("Enter the filename: "); filename

The File. Reader and Buffered. Reader Classes System. out. print("Enter the filename: "); filename = Keyboard. read. String(); File. Reader freader = new File. Reader(filename); Buffered. Reader input. File = new Buffered. Reader(freader); o The lines above: n n Prompt the user for a filename. Get the filename from the user. Create an instance of the File. Reader class that is associated with the filename. Create an instance of the Buffered. Reader class that buffers the instance of the File. Reader class.

The File. Reader and Buffered. Reader Classes o Once an instance of Buffered. Reader

The File. Reader and Buffered. Reader Classes o Once an instance of Buffered. Reader is created, lines of text can be read in. customer. Name = input. File. read. Line(); o o A file pointer is created when the file is first opened. As the file is read, the pointer moves to indicate the text that is to be read next.

Exceptions o o o The File. Reader and Buffered. Reader classes can throw exceptions.

Exceptions o o o The File. Reader and Buffered. Reader classes can throw exceptions. A throws IOException clause needs to be placed on the method header of the method that instantiates a File. Reader or Buffered. Reader object. Also, any method that uses a File. Reader or Buffered. Reader needs a throws IOException clause.

Detecting The End of a File o The read. Line() method of the Buffered.

Detecting The End of a File o The read. Line() method of the Buffered. Reader class will return null if the end of the file has been reached. File. Reader freader = new File. Reader(filename); Buffered. Reader input. File = new Buffered. Reader(freader); // Read the first item. String str = input. File. read. Line(); // If an item was read, display it // and read the remaining items. while (str != null) { System. out. println(str); str = input. File. read. Line(); } input. File. close(); // close the file when done.

Reading a File Flowchart Open the file Read the first item (priming read) Did

Reading a File Flowchart Open the file Read the first item (priming read) Did read. Line() return null? Close the file Process the item Read next item

File. Read. Demo. java o o o import java. util. Scanner; // Needed for

File. Read. Demo. java o o o import java. util. Scanner; // Needed for the Scanner class import java. io. *; // Needed for file classes public class File. Read. Demo { public static void main(String[] args) throws IOException { String filename; // File name String friend. Name; // Friend's name Scanner keyboard = new Scanner(System. in); System. out. print("Enter the filename: "); filename = keyboard. next. Line();

File. Read. Demo. java o o o o o File. Reader freader = new

File. Read. Demo. java o o o o o File. Reader freader = new File. Reader(filename); Buffered. Reader input. File = new Buffered. Reader(freader); friend. Name = input. File. read. Line(); while (friend. Name != null) { System. out. println(friend. Name); friend. Name = input. File. read. Line(); } input. File. close(); } }