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.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Advertisements

1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
Lecture 15: I/O and Parsing
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
Chapter 9 Streams and File I/O Overview of Streams and File I/O
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
CS102--Object Oriented Programming Lecture 13: File I/O Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
Unit 211 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Unit 201 File IO Binary Files Reading and Writing Binary Files Writing Objects to files Reading Objects from files.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 12 File Input and Output.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 91 Streams and File I/O Chapter 9. 2 Reminders Project 6 released: due Nov 10:30 pm Project 4 regrades due by midnight tonight Discussion.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Java File I/O (Continued). File I/O in Java Like every other programming language, Java supports the writing to and reading from different files with.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
CS0007: Introduction to Computer Programming File IO and Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 9 l Streams and Simple File I/O l Exception Handling with File.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
 Pearson Education, Inc. All rights reserved Files and Streams.
Chapter 9 1 Chapter 9 – Part 2 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 10 File I/O Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Chapter 9Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Project 6 due on Thursday March 31 (3 weeks)
Up to slide 46 for 111. Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Basic Text File Input/Output
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CSS161: Fundamentals of Computing
Streams and File I/O Chapter 9 Chapter 9.
Chapter 17 Binary I/O Dr. Clincy - Lecture.
Streams and File I/O Chapter 14.
CSS 161: Fundamentals of Computing
Comp 249 Programming Methodology
Computer Programming with JAVA
Chapter 10 File I/O Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc.
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

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 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; ……

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

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

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

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 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.

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;

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?

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

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!

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

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.

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?

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.

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); }

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); }

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!

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); }

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 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.

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

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.

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: 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

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.

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 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

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));

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