Download presentation
Presentation is loading. Please wait.
Published byDevyn Babbitt Modified over 9 years ago
1
Java File I/O
2
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
3
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; ……
4
System.out.printf(“ ”, 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 We have learned some screen stream using System.out.* functions and Scanner and System.in objects Screen I/O streams
5
System.out.printf(“ ”, 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 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) We have learned some screen stream using System.out.* functions and Scanner and System.in objects
6
System.out.printf(“ ”, 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 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.FileInputStreamFileOutputStream All other stream types are built on byte streams, such as the character stream for text file reading and writing. We have learned some screen stream using System.out.* functions and Scanner and System.in objects
7
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?
8
How to write to a text file Use PrintWriter class 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.
9
How to write to a text file Use PrintWriter class The following are the classes that you need to import. import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException;
10
How to write to a text file Use PrintWriter class 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?
11
How to write to a text file Use PrintWriter class 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 PrintWriter outputStreamName; outputStreamName = new PrintWriter( new FileOutputStream (FileName)); a string representing the file name as its argument PrintWriter takes the anonymous FileOutputStream object as its argument
12
How to write to a text file Use PrintWriter class 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 PrintWriter outputStreamName; outputStreamName = new PrintWriter(FileName); Correction: You now can use the following format to create the PrintWriter class.n!
13
How to write to a text file Use PrintWriter class PrintWriter outputStreamName; 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
14
How to write to a text file Use PrintWriter class PrintWriter outputStreamName; 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.
15
How to write to a text file Use PrintWriter class 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?
16
How to write to a text file Use PrintWriter class 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.
17
How to write to a text file Use PrintWriter class In case that the file cannot be created successfully, a FileNotFoundException exception can be thrown to avoid writing to null object. PrintWriter outputStreamName; try { outputStreamName = new PrintWriter( new FileOutputStream (FileName)); outputStreamName.print(…); …… } catch(FileNotFoundException e) { System.out.println(“File “+FileName”+”cannot be found.”); System.exit(0); }
18
How to write to a text file Use PrintWriter class In case that the file cannot be created successfully, a FileNotFoundException exception can be thrown to avoid writing to null object. throw happens in this calling More to come on exception handling! PrintWriter outputStreamName; try { outputStreamName = new PrintWriter( new FileOutputStream (FileName)); outputStreamName.print(…); …… } catch(FileNotFoundException e) { System.out.println(“File “+FileName”+”cannot be found.”); System.exit(0); }
19
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. outputStreamName = new PrintWriter( new FileOutputStream(FileName, true)); Use the following format to open the file!
20
Example import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; public class WriteTextFileDemo { public static void main (String[] args) { PrintWriter outputStreamName; 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(FileNotFoundException e) { System.out.println("File "+Filename+"cannot be found."); System.exit(0); }
21
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.
22
Example Read one integer from the file at a time. Integers are separated by empty space. Read one line of string.
23
Example Given the input file The output will be
24
Example Input file This example assumes the program knows the format of the file.
25
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() ……
26
Testing the end of the text file Example: adding line number to the file
27
Testing the end of the text file Example: adding line number to the file
28
Testing the end of the text file Example: adding line number to the file Given input file: The output file will be
29
Read from a text file Using BufferReader class An object of the class BufferedReader has the methods read and readLine. import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException; The following classes need to be imported.
30
Read from a text file Using BufferReader class BufferedReader readerObject; readerObject = new BufferedReader(new FileReader(FileName)); BufferedReader has no constructor that takes a file name as its argument, and needs FileReader, to convert the file name to an object that can be used as an argument. a string representing the file name as its argument BufferedReader takes the anonymous FileReader object as its argument
31
Read from a text file Using BufferReader class BufferedReader readerObject; 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 readLine method is the same method used to read from the keyboard, but in this case it would read from a file. The read method reads a single character, and returns a value (of type int ) that corresponds to the character read.
32
Using BufferReader class to read from a text file
33
May throw a FileNotFoundException May throw an IOException
34
Using BufferReader class to read from a text file Given input file Output will be
35
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.
36
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
37
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
38
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"));
39
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
40
Example Change the file location of the previous example…
41
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
42
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;
43
Opening a Binary File for Output An ObjectOutputStream object is created and connected to a binary file as follows: ObjectOutputStream outputStreamName = 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
44
Opening a Binary File for Output ObjectOutputStream outputStreamName = 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.
45
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;
46
Opening a Binary File for Reading An ObjectInputStream object is created and connected to a binary file as follows: ObjectInputStream inStreamName = new ObjectInputStream(new FileInputStream(FileName)); The constructor for FileInputStream may throw a FileNotFoundException The constructor for ObjectInputStream may throw an IOException Each of these must be handled
47
Opening a Binary File for Reading 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. ObjectInputStream inStreamName = new ObjectInputStream(new FileInputStream(FileName));
48
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.