Presentation is loading. Please wait.

Presentation is loading. Please wait.

File Input and Output.

Similar presentations


Presentation on theme: "File Input and Output."— Presentation transcript:

1 File Input and Output

2 File Input Input can be read from a variety of sources.
Files are a primary source of input To read from a file, we must connect our program to a file using a Stream, and we can buffer the data in this Stream with a BufferedReader

3 File Input Input can be read from a variety of sources.
Files are a primary source of input To read from a file, we must connect our program to a file using a Stream, and we can buffer the data in this Stream with a BufferedReader

4 Java File Input Several standard classes are helpful
java.io.File – stores information about a file on a computer drive java.io.FileReader – used to translate data bytes received from File objects into a stream of characters Java.io.BufferedReader – used to buffer (store) input received from a FileReader object (stores input as strings).

5 Example of File Input System.out.print( "Enter the filename: " ); // Prompt user for a file name String fileName = stdin.readLine(); // get a file name from the user File file = new File( fileName ); // create a File object if ( file.exists() ) { // check that the file exists BufferedReader inFile = new BufferedReader(new FileReader( file ) ); // Read in a line of the file String line = inFile.readLine(); // if the line is not null, print it back to the screen while ( line != null ){ System.out.println( line ); line = inFile.readLine(); } // Close the buffered reader input stream attached to the file inFile.close();

6 File input Hints Don’t forget to import java.io.*;
File IO can cause Exceptions! We need to take care of these! Do not assume readLine( ) will return valid data Close the BufferedReader object when you’re done reading data from the file

7 File input Hints Questions??

8 StringTokenizer Each line in a file might contain multiple pieces of information StringTokenizer is an easy way to divide these pieces into smaller strings Ex. – A file might store a saved game and a players information (points, lives, level, etc.) Player1:2500:3:21

9 StringTokenizer Declared and defined: StringTokenizer <name>;
<name> = new StringTokenizer(String s,String delimiter); s is the string to break into tokens (smaller strings Delimiter is the string that is used to divide s into tokens Example: String info = “Player1:2500:3:21” StringTokenizer st; st = new StringTokenizer( info, “:”);

10 StringTokenizer We can then access the individual tokens with two StringTokenizer methods: hasMoreTokens() – true if tokens are left nextToken( ) – returns next token (a String) while(st.hasMoreTokens( ) ){ String s = st.nextToken( ); // DO something with s } S will be these Strings: “Player1”,”2500”,”3”,”21”

11 StringTokenizer This is much like Collections
It is useful in breaking up lines in a file into smaller data items It is NOT the best option in all cases Remember to Convert to numbers from Strings if necessary

12 StringTokenizer Questions??

13 File Output Writing data to a file is similar to writing data to the console You will open a file for writing and then print to that file any data that you would like to store there You must remember to close the file or risk having some data not be written and saved to the file

14 File Output We will use each of these classes.
FileWriter - used to open a file and connect an output stream to it. PrintWriter - used to write strings of characters (instead of bytes) to any Writer object.

15 File Output When you intend to write data to a file, you should consider what the appropriate action to take is if the file already exists. Overwrite?, Cancel?, Choose a different file? Ask the user is a good choice The exists( ) method of the File class can help you decide what to do

16 File Output // Create a FileWriter attached to a file named "out.txt".
FileWriter fw = new FileWriter( "out.txt", false ); // Create a PrintWriter PrintWriter pw = new PrintWriter( fw, true ); // Buffer some data to write to the file (doesn't actually write until flush) pw.print( "Some test data that will be written when flush is called."); // Flush all buffered data to the file. pw.flush(); // Write some data and automatically flush it to the file. pw.println( data ); // Close the PrintWriter for added safety. pw.close();

17 File Output PrintWriter is easy because you are already familiar with the print() and println() We must be careful to choose AND REMEMBER how we construct the object Will it always flush the data buffer? It is safer, but less efficient to always flush.  It is more efficient to wait until the buffer is full before writing to disk  Always close the PrintWriter object

18 File Output Questions???

19 Conclusion Input and output using the standard Java library of classes is somewhat more complex than using javabook2 classes.  Experiment and practice with the code here and online and you will be able to perform some of the most common input and output operations in your Java programs.


Download ppt "File Input and Output."

Similar presentations


Ads by Google