+ All Categories
Home > Documents > Java File I/O. File I/O is important! Being able to write and read from files is necessary and is...

Java File I/O. File I/O is important! Being able to write and read from files is necessary and is...

Date post: 02-Apr-2015
Category:
Upload: devyn-babbitt
View: 213 times
Download: 1 times
Share this document with a friend
48
Java File I/O
Transcript
Page 1: 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.

Java File I/O

Page 2: 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.

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

Page 3: 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.

File I/O in JavaLike 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;……

Page 4: 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.

System.out.printf(“<formatting>”, var1, var2,…);System.out.print(String…); //in same lineSystem.out.println(String…); //next line

import java.util.Scanner //for inputScanner keyboard = new Scanner(System.in);int var1 = keyboard.nextInt();double var2 = keyboard.nextDouble();String s1 = keyboard.next(); // read one wordString 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

Page 5: 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.

System.out.printf(“<formatting>”, var1, var2,…);System.out.print(String…); //in same lineSystem.out.println(String…); //next line

import java.util.Scanner //for inputScanner keyboard = new Scanner(System.in);int var1 = keyboard.nextInt();double var2 = keyboard.nextDouble();String s1 = keyboard.next(); // read one wordString 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

Page 6: 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.

System.out.printf(“<formatting>”, var1, var2,…);System.out.print(String…); //in same lineSystem.out.println(String…); //next line

import java.util.Scanner //for inputScanner keyboard = new Scanner(System.in);int var1 = keyboard.nextInt();double var2 = keyboard.nextDouble();String s1 = keyboard.next(); // read one wordString 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.

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

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

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

Page 8: 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.

How to write to a text fileUse 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.

Page 9: 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.

How to write to a text fileUse PrintWriter class

The following are the classes that you need to import.

import java.io.PrintWriter;import java.io.FileOutputStream;import java.io.FileNotFoundException;

Page 10: 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.

How to write to a text fileUse 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?

Page 11: 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.

How to write to a text fileUse 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

Page 12: 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.

How to write to a text fileUse 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!

Page 13: 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.

How to write to a text fileUse 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

Page 14: 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.

How to write to a text fileUse 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 usingoutputStreamName.close();

This allows the system to release any resources used to connect the stream to the file.

Page 15: 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.

How to write to a text fileUse 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?

Page 16: 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.

How to write to a text fileUse 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.

Page 17: 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.

How to write to a text fileUse 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);}

Page 18: 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.

How to write to a text fileUse 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);}

Page 19: 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.

Appending to a text fileIn 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!

Page 20: 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.

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

Page 21: 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.

Read from a text fileUsing 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.

Page 22: 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.

Example

Read one integer from the file at a time. Integers are separated by empty space.

Read one line of string.

Page 23: 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.

Example

Given the input file

The output will be

Page 24: 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.

Example

Input file

This example assumes the program knows the format of the file.

Page 25: 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.

Testing the end of the text fileThis 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()……

Page 26: 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.

Testing the end of the text fileExample: adding line number to the file

Page 27: 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.

Testing the end of the text fileExample: adding line number to the file

Page 28: 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.

Testing the end of the text fileExample: adding line number to the file

Given input file:

The output file will be

Page 29: 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.

Read from a text fileUsing 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.

Page 30: 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.

Read from a text fileUsing 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

Page 31: 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.

Read from a text fileUsing 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.

Page 32: 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.

Using BufferReader class to read from a text file

Page 33: 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.

Using BufferReader class to read from a text file

May throw a FileNotFoundException

May throw an IOException

Page 34: 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.

Using BufferReader class to read from a text file

Given input file

Output will be

Page 35: 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.

Testing the end of the text fileUsing 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.

Page 36: 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.

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

Page 37: 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.

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

Page 38: 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.

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

Page 39: 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.

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

Page 40: 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.

Example

Change the file location of the previous example…

Page 41: 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.

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

Page 42: 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.

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;

Page 43: 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.

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

Page 44: 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.

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.

Page 45: 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.

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;

Page 46: 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.

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

Page 47: 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.

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

Page 48: 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.

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


Recommended