490 likes | 667 Views
Java File I/O. File I/O is important!. Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include but not limited to Various data analysis applications Data visualization Scientific computing Graphics and gaming
E N D
File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. • Examples include but not limited to • Various data analysis applications • Data visualization • Scientific computing • Graphics and gaming • Information management systems • Log and run-time information saving in HPC • …… • Pretty much every major application
File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with different formats. It is achieved via the following set of classes java.io.PrintWriter; java.io.FileOutputStream; java.util.Scanner; java.io.FileInputStream; java.io.BufferedReader; java.io.FileReader; ……
Screen I/O streams We have learned some screen stream using System.out.* functions and Scanner and System.in objects System.out.printf(“<formatting>”, var1, var2,…); System.out.print(String…); //in same line System.out.println(String…); //next line import java.util.Scanner//for input Scanner keyboard = new Scanner(System.in); int var1 = keyboard.nextInt(); double var2 = keyboard.nextDouble(); String s1 = keyboard.next(); // read one word String s2 = keyboard.nextline(); //read one line
Screen I/O streams We have learned some screen stream using System.out.* functions and Scanner and System.in objects System.out.printf(“<formatting>”, var1, var2,…); System.out.print(String…); //in same line System.out.println(String…); //next line import java.util.Scanner//for input Scanner keyboard = new Scanner(System.in); int var1 = keyboard.nextInt(); double var2 = keyboard.nextDouble(); String s1 = keyboard.next(); // read one word String s2 = keyboard.nextline(); //read one line • A stream is an object that allows for the flow of data between your program and some I/O device or some file. • Input stream (from external content to the program) • Output stream (from the program to external devices or files)
Screen I/O streams We have learned some screen stream using System.out.* functions and Scanner and System.in objects System.out.printf(“<formatting>”, var1, var2,…); System.out.print(String…); //in same line System.out.println(String…); //next line import java.util.Scanner//for input Scanner keyboard = new Scanner(System.in); int var1 = keyboard.nextInt(); double var2 = keyboard.nextDouble(); String s1 = keyboard.next(); // read one word String s2 = keyboard.nextline(); //read one line Byte stream: perform input and output of 8-bit bytes. In the later File IO FileInputStream and FileOutputStream are byte streams that allow the program to read and write binary files. All other stream types are built on byte streams, such as the character streamfor text file reading and writing.
Files There are typically two types of files that a program will handle despite different formats. Text files: also be called ASCII files because the data they contain uses an ASCII encoding scheme. They are human readable and can be moved from one computer to another (same ASCII characters). Binary files: consist of a sequence of binary digits. They are designated to be read by programs, and NOT by human. They are typically more efficient (to load and store) than text files. But they could be machine dependent due to the different bytes for the same digits. Java does not have this issue though. Why?
How to write to a text file Use PrintWriterclass It has the similar methods as System.out such as print(…) and println(…) Rather than writing on the screen, these methods write to the specified text file.
How to write to a text file Use PrintWriterclass • The following are the classes that you need to import. • import java.io.PrintWriter; • import java.io.FileOutputStream; • import java.io.FileNotFoundException;
How to write to a text file Use PrintWriterclass • The following are the classes that you need to import. • import java.io.PrintWriter; • import java.io.FileOutputStream; • import java.io.FileNotFoundException; So why do we need FileOutputStream?
How to write to a text file Use PrintWriterclass • The class PrintWriter has no constructor that takes a file name as its argument • It uses another class, FileOutputStream, to convert a file name to an object that can be used as the argument to its (the PrintWriter) constructor PrintWriteroutputStreamName; outputStreamName = new PrintWriter( new FileOutputStream (FileName)); PrintWriter takes the anonymous FileOutputStream object as its argument • a string representing the file name as its argument
How to write to a text file Use PrintWriterclass Correction: You now can use the following format to create the PrintWriterclass.n! • The class PrintWriter has no constructor that takes a file name as its argument • It uses another class, FileOutputStream, to convert a file name to an object that can be used as the argument to its (the PrintWriter) constructor PrintWriteroutputStreamName; outputStreamName = new PrintWriter(FileName);
How to write to a text file Use PrintWriterclass PrintWriteroutputStreamName; outputStreamName = new PrintWriter( new FileOutputStream (FileName)); If the file is open successfully, the methods, print(…)and println(…),can be used to output text information into the file. • If the file already exists, then doing this causes the old contents to be lost • If the file does not exist, then a new, empty file named FileName is created
How to write to a text file Use PrintWriterclass PrintWriteroutputStreamName; outputStreamName = new PrintWriter( new FileOutputStream (FileName)); If the file is open successfully, the methods, print(…)and println(…),can be used to output text information into the file. After the writing is finished, the file needs to be closed using • outputStreamName.close(); This allows the system to release any resources used to connect the stream to the file.
How to write to a text file Use PrintWriterclass • The following are the classes that you need to import. • import java.io.PrintWriter; • import java.io.FileOutputStream; • import java.io.FileNotFoundException; So why do we need FileNotFoundException?
How to write to a text file Use PrintWriterclass In case that the file cannot be created successfully, a FileNotFoundException exception can be thrown to avoid writing to null object. This exception can also be thrown when attempting to read an non-existing file.
How to write to a text file Use PrintWriterclass In case that the file cannot be created successfully, a FileNotFoundExceptionexception can be thrown to avoid writing to null object. PrintWriteroutputStreamName; try { outputStreamName= new PrintWriter( new FileOutputStream (FileName)); outputStreamName.print(…); …… } catch(FileNotFoundException e) { System.out.println(“File “+FileName”+”cannot be found.”); System.exit(0); }
How to write to a text file Use PrintWriterclass In case that the file cannot be created successfully, a FileNotFoundExceptionexception can be thrown to avoid writing to null object. PrintWriteroutputStreamName; try { outputStreamName= new PrintWriter( new FileOutputStream (FileName)); outputStreamName.print(…); …… } catch(FileNotFoundException e) { System.out.println(“File “+FileName”+”cannot be found.”); System.exit(0); } throw happens in this calling More to come on exception handling!
Appending to a text file In some situations, you do not want to overwrite what has been recorded in the existing file. The new output will be appended to the previous output. Use the following format to open the file! outputStreamName = new PrintWriter( new FileOutputStream(FileName, true));
Example import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; public class WriteTextFileDemo { public static void main (String[] args) { PrintWriteroutputStreamName; String Filename = "test.txt"; try { outputStreamName = new PrintWriter(new FileOutputStream (Filename)); outputStreamName.println("test text file!"); outputStreamName.println("succeeded!"); // Do other fancy output … outputStreamName.close(); } catch(FileNotFoundExceptione) { System.out.println("File "+Filename+"cannot be found."); System.exit(0); } } }
Read from a text file Using Scannar class • Simply replace the argument System.in (to the Scanner constructor) with a suitable stream that is connected to the text file • Scanner StreamObject= • new Scanner(new FileInputStream(FileName)); Methods of the Scanner class for reading input behave the same whether reading from the keyboard or reading from a text file.
Example Read one integer from the file at a time. Integers are separated by empty space. Read one line of string.
Example Given the input file The output will be
Example Input file This example assumes the program knows the format of the file.
Testing the end of the text file This is a very practical problem. The program needs to stop reading when reaching the end of the file. Otherwise -> exception… When using the Scannar object to read the text file, the following methods can be used to determine whether the program is reaching the end of the file. hasNextInt() hasNextShort() hasNextLong() hasNextByte() hasNextDouble() hasNextLine() ……
Testing the end of the text file Example: adding line number to the file
Testing the end of the text file Example: adding line number to the file
Testing the end of the text file Example: adding line number to the file Given input file: The output file will be
Read from a text file Using BufferReaderclass • An object of the class BufferedReader has the methods read and readLine. The following classes need to be imported. • import java.io.BufferedReader; • import java.io.FileReader; • import java.io.FileNotFoundException; • import java.io.IOException;
Read from a text file Using BufferReaderclass BufferedReaderhas no constructor that takes a file name as its argument, and needsFileReader, to convert the file name to an object that can be used as an argument. • BufferedReaderreaderObject; • readerObject= new BufferedReader(new • FileReader(FileName)); BufferedReadertakes the anonymous FileReaderobject as its argument • a string representing the file name as its argument
Read from a text file Using BufferReaderclass • BufferedReaderreaderObject; • readerObject= new BufferedReader(new • FileReader(FileName)); After the file is successfully opened, the readLine() and read() methods can be used to read from the file. • The readLinemethod is the same method used to read from the keyboard, but in this case it would read from a file. • The readmethod reads a single character, and returns a value (of type int) that corresponds to the character read.
Using BufferReader class to read from a text file May throw a FileNotFoundException May throw an IOException
Using BufferReader class to read from a text file Given input file Output will be
Testing the end of the text file Using BufferReader class to read from a text file • When using the readLine()method, it will return null if reaching or trying to read beyond the end of the file. • When using the read()method, it will return -1 if reaching or trying to read beyond the end of the file.
Reading Numbers • Unlike the Scanner class, the class BufferedReader has no methods to read a number from a text file • Instead, a number must be read in as a string, and then converted to a value of the appropriate numeric type using one of the wrapper classes • To read in a single number on a line by itself, first use the method readLine, and then use Integer.parseInt, Double.parseDouble, etc. to convert the string into a number • If there are multiple numbers on a line, StringTokenizer can be used to decompose the string into tokens, and then the tokens can be converted as described above
Path Names • When a file name is used as an argument to a constructor for opening a file, it is assumed that the file is in the same directory or folder as the one in which the program is run • If it is not in the same directory, the full or relative path name must be given
Path Names • The way path names are specified depends on the operating system • A typical UNIX path name that could be used as a file name argument is "/user/sallyz/data/data.txt" • A BufferedReader input stream connected to this file is created as follows: BufferedReader inputStream = new BufferedReader(new FileReader("/user/sallyz/data/data.txt"));
Path Names • The Windows operating system specifies path names in a different way • A typical Windows path name is the following: C:\dataFiles\goodData\data.txt • A BufferedReader input stream connected to this file is created as follows: BufferedReader inputStream = new BufferedReader(new FileReader ("C:\\dataFiles\\goodData\\data.txt")); • Note that in Windows \\ must be used in place of \, since a single backslash denotes an the beginning of an escape sequence
Example Change the file location of the previous example…
Binary File I/O • Binary files store data in the same format used by computer memory to store the values of variables • No conversion needs to be performed when a value is stored or retrieved from a binary file • Java binary files, unlike other binary language files, are portable • A binary file created by a Java program can be moved from one computer to another • These files can then be read by a Java program, but only by a Java program
Writing Simple Data to a Binary File • The class ObjectOutputStream is a stream class that can be used to write to a binary file • An object of this class has methods to write strings, values of primitive types, and objects to a binary file • A program using ObjectOutputStream needs to import several classes from package java.io: import java.io.ObjectOutputStream; import java.io.FileOutStream; import java.io.IOException;
Opening a Binary File for Output • An ObjectOutputStream object is created and connected to a binary file as follows: ObjectOutputStreamoutputStreamName = new ObjectOutputStream(new FileOutputStream(FileName)); • The constructor for FileOutputStream may throw a FileNotFoundException • The constructor for ObjectOutputStream may throw an IOException • Each of these must be handled
Opening a Binary File for Output ObjectOutputStreamoutputStreamName = new ObjectOutputStream(new FileOutputStream(FileName)); • Methods used to output primitive values include writeInt, writeDouble, writeChar, and writeBoolean • The method writeUTF can be used to output values of type String. • The stream should be closed after writing.
Reading Simple Data from a Binary File • The class ObjectInputStream is a stream class that can be used to read from a binary file • An object of this class has methods to read strings, values of primitive types, and objects from a binary file • A program using ObjectInputStream needs to import several classes from package java.io: import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.IOException;
Opening a Binary File for Reading • An ObjectInputStreamobject is created and connected to a binary file as follows: ObjectInputStreaminStreamName = new ObjectInputStream(new FileInputStream(FileName)); • The constructor for FileInputStreammay throw a FileNotFoundException • The constructor for ObjectInputStreammay throw an IOException • Each of these must be handled
Opening a Binary File for Reading ObjectInputStreaminStreamName = new ObjectInputStream(new FileInputStream(FileName)); • Methods used to input primitive values include readInt, readDouble, readChar, and readBoolean • The method readUTF is used to input values of type String. • If the file contains multiple types, each item type must be read in exactly the same order it was written to the file. • The stream should be closed after reading.
Checking for the End of a Binary File the Correct Way • All of the ObjectInputStream methods that read from a binary file throw an EOFException when trying to read beyond the end of a file • This can be used to end a loop that reads all the data in a file • Note that different file-reading methods check for the end of a file in different ways • Testing for the end of a file in the wrong way can cause a program to go into an infinite loop or terminate abnormally