CS2312 Lecture 9

Input/Output

Streams

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 a buffer between the data source and destination

Input stream: a stream that provides input to a program.   System.in is an input stream

Output stream: a stream that accepts output from a program.   System.out is an output stream

A stream connects a program to an I/O object.

  • System.out connects a program to the screen
  • System.in connects a program to the keyboard  

Binary Files & Text Files

Text files

  • one byte per character for ASCII, the most common code
  • for example, Java source files are text files
  • Text files are more readable by humans  

Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data

  • these files are easily read by the computer but not humans
  • for exmaple, the compiled c++ codes are binary files.
  • Binary files are more efficient 

 

Text File I/O

Important classes for text file output (to the file)

  • FileWriter
  • BufferedWriter
  • PrintWriter

Important classes for text file input (from the file):

  • FileReader
  • BufferedReader
  • Scanner  

To use these classes your program needs a line like the following: import java.io.*; 

 

FileReader and FileWriter

The two main classes for reading and writing text files.

  • A file is opened when its name is passed to their constructors.
  • Files should be closed (via close) when finished with.
  • Their read and write methods deal with char and char[].  
try{
    // Try to open the file.
    FileReader inputFile = new FileReader(filename);
    // Process the file's contents.
    ...
    // Close the file now that it is finished with.
    inputFile.close();
}
catch(FileNotFoundException e){
    System.out.println("Unable to open "+filename);
}
catch(IOException e){
    // The file could not be read or closed.
    System.out.println("Unable to process "+filename);
}

Copiny a Text File

static void copyFile(FileReader inputFile, FileWriter outputFile) throws IOException {
    final int bufferSize = 1024;
    char[] buffer = new char[bufferSize];
    // Read the first chunk of characters.
    int numberRead = inputFile.read(buffer);
    while(numberRead > 0){
        // Write out what was read.
        outputFile.write(buffer,0,numberRead);
        numberRead = inputFile.read(buffer);
    }
    outputFile.flush();
}

Reading Single Characters

static void copyFile(FileReader inputFile,FileWriter outputFile){
    try{
        // Read the first character.
        int nextChar = inputFile.read();
        // Have we reached the end of file?
        while(nextChar != -1){
            outputFile.write(nextChar);
            // Read the next character.
            nextChar = inputFile.read();
        }
        outputFile.flush();
    }
    catch(IOException e){
        System.out.println("Unable to copy a file.");
    }
}

Buffering

Not buffered: each byte is read/written from/to disk as soon as possible

  • “little” delay for each byte  
  • A disk operation per byte---higher overhead

Buffered: reading/writing in “chunks”

  • Some delay for some bytes
  • A disk operation per a buffer of bytes---lower overhead  

BufferedReader and BufferedWriter

try{
    FileReader in = new FileReader(infile);
    BufferedReader reader = new BufferedReader(in);
    FileWriter out = new FileWriter(outfile);
    BufferedWriter writer = new BufferedWriter(out);
    ...
    reader.close();
    writer.close();
}
catch(FileNotFoundException e){
    System.out.println(e.getMessage());
}
catch(IOException e){
    System.out.println(e.getMessage());
}

Line-by-Line Copying

BufferedReader reader = new BufferedReader(...);
// Read the first line.
String line = reader.readLine();
// null returned on EOF.
while(line != null){
    // Write the whole line.
    writer.write(line);
    // Add the newline character.
    writer.newLine();
    // Read the next line.
    line = reader.readLine();
}

 

Text Output

PrintWriter

try{
    FileWriter out = new FileWriter(outfile);
    PrintWriter writer = new PrintWriter(out);
    
    writer.println(…);
    writer.format(“%d…”,…);
    writer.close();
}
catch(IOException e){
    System.out.println(e.getMessage());
}

To open a text file for output: connect a text file to a stream for writing

PrintWriter outputStream = new PrintWriter(new FileWriter("out.txt"));  

 

Similar to the long way:

FileWriter s = new FileWriter("out.txt");
PrintWriter outputStream = new PrintWriter(s);  

Goal: create a PrintWriter object  which uses FileWriter to open a text file

FileOutputStream “connects” PrintWriter to a text file.  

Methods for PrintWriter

  • Similar to methods for System.out -  println -  outputStream.println(count + " " + line);  
  • print
  • format
  • flush: write buffered output to disk
  • close: close the PrintWriter stream (and file)   
import java.io.*;
import java.util.Scanner;

public class TextFileOutputDemo {
    public static void main(String[] args){
        PrintWriter outputStream = null;
        try{
            outputStream = new PrintWriter(new FileWriter("/Users/charon/Documents/IdeaProjects/CS2312/src/IO/out.txt"));
        }
        catch(FileNotFoundException e){
            System.out.println("Error opening the file out.txt. "+ e.getMessage());
                    System.exit(0);
        }catch(IOException e){
            // The file could not be read or closed.
            System.out.println("Unable to process ");
        }
        System.out.println("Enter three lines of text:");
        Scanner keyboard = new Scanner(System.in);
        String line = null;
        int count;
        for (count = 1; count <= 3; count++){
            line = keyboard.nextLine();
            outputStream.println(count + " " + line);  //writing to the file
        }
        outputStream.close();
        System.out.println("... written to out.txt.");
    }
}
  • Opening an output file creates an empty file  
  • Opening an output file creates a new file if it does not already exist  
  • Opening an output file that already exists eliminates the old file and creates a new, empty one. (data in the original file is lost)

Two reasons why need to Close a File:

  • 1.  To make sure it is closed if a program ends abnormally (it could get damaged if it is left open).  
  • 2.  A file opened for writing must be closed before it can be opened for reading. Although Java does have a class that opens a file for both reading and writing, it is not used in this course. 

 

Text Input

To open a text file for input: connect a text file to a stream for reading

  • Goal: a BufferedReader object,  which uses FileReader to open a text file
  • FileReader “connects” BufferedReader to the text file

For example:

BufferedReader smileyInStream =  new BufferedReader(new FileReader(“smiley.txt")); 

Similarly, the long way:

FileReader s = new FileReader(“smiley.txt"); 
BufferedReader smileyInStream = new BufferedReader(s);   

Methods for BufferedReader

  • readLine: read a line into a String
  • no methods to read numbers directly, so read numbers as Strings and then convert them 
  • read: read a char at a time
  • close: close BufferedReader stream  
package IO;

import java.io.*;
import java.util.Scanner;

public class Buffer_Reader {
    public static void main(String[] args)
    {
        String fileName = null;  // outside try block, can be used in catch
        try
        {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter file name:");
            fileName = keyboard.next();
            BufferedReader inputStream = new BufferedReader(new FileReader(fileName));
            String line = null;
            line = inputStream.readLine();
            System.out.println("The first line in " + fileName + " is:");
            System.out.println(line);
            // . . . code for reading second line not shown here . . .
            inputStream.close();
        }
        catch(FileNotFoundException e)
        {
            System.out.println("File " + fileName + " not found.");
        }
        catch(IOException e)
        {
            System.out.println("Error reading from file " + fileName);
        }
    }
}

Reading Words in a String: Using StringTokenizer Class

There are BufferedReader methods to read a line and a character, but not just a single word  

StringTokenizer can be used to parse a line into words

  • import java.util.*
  • some of its useful methods are shown in the text e.g. test if there are more tokens
  • you can specify delimiters (the character or characters that separate words). The default delimiters are "white space" (space, tab, and newline) 
String inputLine = keyboard.nextLine();
StringTokenizer wordFinder =
            new StringTokenizer(inputLine, " \n.,");
//the second argument is a string of the 4 delimiters
while(wordFinder.hasMoreTokens())
{
   System.out.println(wordFinder.nextToken());
}
Input: Question,2a.or !twoA." 
Output: 
    Question
    2a
    or
    !twoA

Testing for End of File in a Text File

  • When readLine tries to read beyond the end of a text file it returns the special value null, so you can test for null to stop processing a text file  
  • read returns -1 when it tries to read beyond the end of a text file. the int value of all ordinary characters is nonnegative  
  • Neither of these two methods (read and readLine) will throw an EOFException. 
int count = 0;
String line = inputStream.readLine();
while (line != null)
{
   count++;
   outputStream.println(count + " " + line);
   line = inputStream.readLine(); 
}

// When using readLine test for null

// When using read test for -1

Scanner

Use Scanner with File: 

Scanner inFile = new Scanner(new File(“in.txt”));

Similar to Scanner with System.in:

Scanner keyboard = new Scanner(System.in); 

Reading in int

Scanner inFile = new Scanner(new File(“in.txt"));
int number;
while (inFile.hasInt()){
    number = inFile.nextInt();
    //
}

Reading in lines of characters

Scanner inFile = new Scanner(new File(“in.txt"));
String line;
while (inFile.hasNextLine()){
    line = inFile.nextLine();
    //
}

Multiple types on one line

// Name, id, balance 
Scanner inFile = new Scanner(new File(“in.txt"));
while (inFile.hasNext()){
    name = inFile.next();
    id = inFile.nextInt();
    balance = inFile.nextFloat();
    // …  new Account(name, id, balance);
  }
--------------------
String line;
while (inFile.hasNextLine()){
    line = inFile.nextLine();
    Scanner parseLine = new Scanner(line)  // Scanner again!
    name = parseLine.next();
    id = parseLine.nextInt();
    balance = parseLine.nextFloat();
    // …  new Account(name, id, balance);
  }
// Name, id, balance 
Scanner inFile = new Scanner(new File(“in.txt"));
String line;
while (inFile.hasNextLine())
  {
     line = inFile.nextLine();
     Account account = new Account(line);
  }
--------------------
public Account(String line) // constructor
{
  Scanner accountLine = new Scanner(line);
  _name = accountLine.next();
  _id = accountLine.nextInt();
  _balance = accountLine.nextFloat();
}

BufferedReader vs Scanner (parsing primitive types)

Scanner

  • nextInt(), nextFloat(), … for parsing types

BufferedReader

  • read(), readLine(), … none for parsing types
  • needs StringTokenizer then wrapper class methods like Integer.parseInt(token) 

BufferedReader vs Scanner (Checking End of File/Stream (EOF))

BufferedReader

  • readLine() returns null
  • read() returns -1  

Scanner

  • nextLine() throws exception
  • needs hasNextLine() to check first
  • nextInt(), hasNextInt(), … 
BufferedReader inFile = …
line = inFile.readline();
while (line != null)
{
  //
  line = inFile.readline();
}

-------------------

Scanner inFile =while (inFile.hasNextLine())
{
  line = infile.nextLine();
  //
}
 
BufferedReader inFile = …
line = inFile.readline();
while (line != null)
{
  //
  line = inFile.readline();
}

-------------------

BufferedReader inFile =while ((line = inFile.readline()) != null)
{
  //
}

Suggestion

Use Scanner with -  File new Scanner(new File(“in.txt”));

Use hasNext…() to check for EOF -  while (inFile.hasNext…())

Use next…() to read - inFile.next…()

 

File input - Scanner inFile = new Scanner(new File(“in.txt”));

File output - 

  • PrintWriter outFile = new PrintWriter(new File(“out.txt”));
  • outFile.print(), println(), format(), flush(), close(), … 

 

FIle Object

BInary File IO

Important classes for binary file output (to the file)

  • ObjectOutputStream
  • FileOutputStream

Important classes for binary file input (from the file):

  • ObjectInputStream
  • FileInputStream

Note that FileOutputStream and FileInputStream are used only for their constructors, which can take file names as arguments. ObjectOutputStream and ObjectInputStream cannot take file names as arguments for their constructors.

To use these classes your program needs a line like the following: import java.io.*; 

ObjectInputStream and ObjectOutputStream:

  • have methods to either read or write data one byte at a time
  • automatically convert numbers and characters into binary. binary-encoded numeric files (files with numbers) are not readable by a text editor, but store data more efficiently

Remember:

  • input means data into a program, not the file
  • similarly, output means data out of a program, not the file 

When using objectOutputStream to putput data to files:

  • The output files are binary and can store any of the primitive data types (int, char, double, etc.) and the String type  
  • The files created can be read by other Java programs but are not printable  
  • The Java I/O library must be imported by including the line: import java.io.*; it contains ObjectOutputStream and other useful class definitions  
  • An IOException might be thrown    

Opening an output file

ObjectOutputStream outputStream = new ObjectOutputStream( new FileOutputStream("numbers.dat"));

The constructor for ObjectOutputStream requires a FileOutputStream argument

The constructor for FileOutputStream requires a String argument the String argument is the output file name

The following two statements are equivalent to the single statement above: 

FileOutputStream middleman =
new FileOutputStream("numbers.dat");
ObjectOutputStream outputStream =
new ObjectOutputSteam(middleman);

ObjectOutputStream Methods

  • writeInt(int n)
  • writeDouble(double x)
  • writeBoolean(boolean b)
  • etc

Note that each write method throws IOException, eventually we will have to write a catch block for it  

Also note that each write method includes the modifier final. final methods cannot be redefined in derived classes 

Closing a File

An Output file should be closed when you are done writing to it  

Use the close method of the class ObjectOutputStream  

outputStream.close();

If a program ends normally it will close any files that are open   

Writing Strings to a File: Another Little Unexpected Complexity

Use the writeUTF method to output a value of type String, there is no writeString method.  

UTF stands for Unicode Text Format, a special version of Unicode  

Unicode: a text (printable) code that uses 2 bytes per character, designed to accommodate languages with a different alphabet or no alphabet (such as Chinese and Japanese) 

When Using ObjectInputStream to Read Data from Files:

  • Input files are binary and contain any of the primitive data types (int, char, double, etc.) and the String type  
  • The files can be read by Java programs but are not printable  
  • The Java I/O library must be imported including the line: import java.io.*; it contains ObjectInputStream and other useful class definitions  
  • An IOException might be thrown 

Opening an Input File

ObjectInputStream inStream = new ObjectInputStream (new FileInputStream("numbers.dat"));

The constructor for ObjectInputStream requires a FileInputStream argument

The constructor for FileInputStream requires a String argument the String argument is the input file name

The following two statements are equivalent to the statement at the top of this slide:  

FileInputStream middleman = new FileInputStream("numbers.dat"); 
ObjectInputStream inputStream = new ObjectInputStream (middleman);

ObjectInputStream Methods

  • readInt()
  • readDouble
  • readBoolean
  • etc

Note that each write method throws IOException  

Also note that each write method includes the modifier final 

 

Input File Exception

A FileNotFoundException is thrown if the file is not found when an attempt is made to open a file  

Each read method throws IOException, we still have to write a catch block for it  

If a read goes beyond the end of the file an EOFException is thrown  

There is no error message(or exception) if you read the wrong data type

Input files can contain a mix of data types, it is up to the programmer to know their order and use the correct read method

ObjectInputStream works with binary, not text files

As with an output file, close the input file when you are done with it 

 

Binary I/O of Class Objects

read and write class objects in binary file  

class must be serializable:

  • import java.io.*
  • implement Serializable interface
  • add implements Serializable to heading of class definition 
public class Species implements Serializable

// to write object to file: writeObject method in ObjectOutputStream
// to read object from file: readObject method in ObjectInputStream
outputStream = new ObjectOutputStream(new FileOutputStream(“Person.records"));
...
Person oneRecord = new Person(“Tommas”, 330222002,”City U of HK”);
...
outputStream.writeObject(oneRecord);

// ClassIODemo Excerpts
inputStream = new ObjectInputStream(new FileInputStream(“Person.records"));
...
Person readOne = null;
...
readOne = (Person)inputStream.readObject(oneRecord);
// readObject returns a reference to type Object so it must be cast to Person before assigning to readOne

The Serializable Interface

Java assigns a serial number to each object written out.

  • If the same object is written out more than once, after the first write only the serial number will be written.
  • When an object is read in more than once, then there will be more than one reference to the same object.  

If a serializable class has class instance variables then they should also be serializable. 

 

I/O Exception

Exception Handling with File I/O

Catching IOExceptions

  • IOException is a predefined class
  • File I/O might throw an IOException
  • catch the exception in a catch block that at least prints an error message and ends the program
  • FileNotFoundException is derived from IOException
    • therefore any catch block that catches IOExceptions also catches FileNotFoundExceptions, put the more specific one first (the derived one) so it catches specifically file-not-found exceptions, then you will know that an I/O error is something other than file-not-found

The EOFException Class

Many (but not all) methods that read from a file throw an end-of-file exception (EOFException) when they try to read beyond the file  

The end-of-file exception can be used in an "infinite" (while(true)) loop that reads and processes data from the file. the loop terminates when an EOFException is thrown  

The program is written to continue normally after the EOFException has been caught   

        try
        {
            ObjectInputStream inputStream =
              new ObjectInputStream(new FileInputStream("numbers.dat"));
            int n;
        
            System.out.println("Reading ALL the integers");
            System.out.println("in the file numbers.dat.");
            try
            {
// Intentional "infinite" loop to process data from input file
                while (true)
                {
                    n = inputStream.readInt();
                    System.out.println(n);
                }
            }
// Loop exits when end-of-file exception is thrown
            catch(EOFException e)
            {
                System.out.println("End of reading from file.");
            }
            inputStream.close();
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Cannot find file numbers.dat.");
        }
        catch(IOException e)
        {
            System.out.println("Problem with input from file numbers.dat.");
        }
//Note order of catch blocks: the most specific is first and the most general last

 

Summary

  • Text files contain strings of printable characters; they look intelligible to humans when opened in a text editor.
  • Binary files contain numbers or data in non-printable codes; they look unintelligible to humans when opened in a text editor.
  • Java can process both binary and text files, but binary files are more common when doing file I/O.
  • The class ObjectOutputStream is used to write output to a binary file. 
  • The class ObjectInputStream is used to read input from a binary file.
  • Always check for the end of the file when reading from a file. The way you check for end-of-file depends on the method you use to read from the file.
  • A file name can be read from the keyboard into a String variable and the variable used in place of a file name.
  • The class File has methods to test if a file exists and if it is read- and/or write-enabled.
  • Serializable class objects can be written to a binary file. 

 


ObjectInputStream和ObjectInputStream类创建的对象被称为对象输入流和对象输出流
创建文件输出流代码:
FileOutputStream file_out = new FileOutputStream(“student.dat”);
ObjectOutputStream object_out = new ObjectOutputStream(file_out);
创建文件输入流代码:
FileInputStream   file   =   new   FileInputStream( "student.dat ");
ObjectInputStream   ois   =   new  ObjectInputStream(file);

FileInputStream,ObjectInputStream:前者是文件输出流,后者是对象输出流.
FileInputStream是ObjectInputStream的子类,所以FileInputStream的引用可以赋给ObjectInputStream,即程序中: inTwo=new ObjectInputStream(inOne); 这个在程序中运用比较普遍.

字符流是Reader和Writer所派生下来的子类,字节流是InputStream和OutputStream所派生下来的子类.

流的分类:
  按内容分:字符流、字节流
  按功能分:输入流、输出流

https://blog.csdn.net/GOALSTAR/article/details/1913972

https://www.cnblogs.com/wsg25/p/7499227.html

https://www.cnblogs.com/fnz0/p/5410856.html

 

posted @ 2018-04-16 00:24  Charonnnnn  阅读(378)  评论(0编辑  收藏  举报