190 likes | 301 Views
Text-File I/O. Text-File Output with PrintWriter. The class PrintWriter is the preferred stream class for writing a text file.
E N D
Text-File Output with PrintWriter • The class PrintWriter is the preferred stream class for writing a text file. • PrintWriter contains a method called println, like the method of the same name we used as System.out.println except it sends output to a text file instead of the screen. • A text file is opened with a statement like: outputStream = new PrintWriter(new FileOutputStream(“out.txt”));
Text-File Output with PrintWriter (cont’d) • The above statement connects the stream named outputStream to the file named out.txt • Making this connection is referred to as opening the file. • When you connect a file to a stream in this way, your program always starts with an empty file. • If the file already exists, the old contents are lost.
Example of File I/O import java.io.*;import java.util.*;public class TextFileOutputDemo{ public static void main(String[] args) { PrintWriter outputStream = null; try { outputStream = new PrintWriter(new FileOutputStream("out.txt")); } catch(FileNotFoundException e) { System.out.println("Error opening the file out.txt."); System.exit(0); } System.out.println("Enter three lines of text:"); String line = null; Scanner keyboard = new Scanner(System.in); int count; for (count = 1; count <= 3; count++) { line = keyboard.nextLine( ); outputStream.println(count + " " + line); } outputStream.close( ); System.out.println("Those lines were written to out.txt."); }}
A File Has Two Names • One name is the real name of the file that is used by the operating system. • The other name is the name of the stream that is connected to the file. This is the name your program uses when it refers to the file. • How you can name the real file depends on your operating system. The name must be a legal name in that system.
FileNotFoundException • This is a poorly named exception. • When it is thrown when you are trying to open a file for output, it doesn’t really mean it could find the file. • It means that for some reason it could not open the file. It might mean that the name was already used for a directory (folder) name, for example.
Closing a File • When your program is finished writing to a file, it should close the stream connected to it, e.g., outputStream.close(); • The class PrintWriter, and every other class for file output or file input streams, has a method named close. • When this method is invoked, the system releases any resources used to connect the stream to the file.
Closing a File (cont’d) • If your program does not close a file before the program ends, Java will close it for your as long as your program ends normally. • If your program ends abnormally with a file still open, the file could be damaged. • It is best to close files in your program as soon as they are no longer needed.
Overwriting a File • When you connect a stream to a text file by using the class PrintWriter in the following way, you always produce an empty file: PrintWriter outputStream = new PrintWriter(new FileOutputStream(“out.txt”)); • If there is no file named out.txt, one will be created. • If out.txt already exists, the existing file will be eliminated and a new empty file will be created.
Appending to a File • If, however, you want append to an existing file, you can connect the file to the output stream as follows: outputStream = new PrintWriter(new FileOutputStream(“out.txt”, true)); • If the file out.txt does not already exist, Java will create an empty file of that name and append the output to the end of this empty file. • If the file out.txt already exists, the old contents will remain and the program’s output will be placed after those contents.
Use toString for Text-File Output • It is common to include a method toString() in classes. • This method should produce a string value that intuitively represents the data in an object. • The method toString has a special property. If you do not include it in an invocation of System.out.println, it is invoked automatically.
Example using a toString Method import java.io.*;import java.util.*;/** Class for data on endangered species. This class is serialized.*/public class Species implements Serializable{ private String name; private int population; private double growthRate; public Species( ) { name = null; population = 0; growthRate = 0; } public Species(String initialName, int initialPopulation, double initialGrowthRate) { name = initialName; if (initialPopulation >= 0) population = initialPopulation; else { System.out.println("ERROR: Negative population."); System.exit(0); } growthRate = initialGrowthRate; }
Example using a toString Method (cont’d) public String toString() { return ("Name = " + name + "\n" + "Population = " + population + "\n" + "Growth rate = " + growthRate + "%"); } public void readInput( ) { Scanner keyboard = new Scanner(System.in); System.out.println("What is the species' name?"); name = keyboard.nextLine( ); System.out.println( "What is the population of the species?"); population = keyboard.nextInt( ); while (population < 0) { System.out.println("Population cannot be negative."); System.out.println("Reenter population:"); population = keyboard.nextInt( ); } System.out.println( "Enter growth rate (percent increase per year):"); growthRate = keyboard.nextDouble( ); }
Example using a toString Method (cont’d) public void writeOutput( ) { System.out.println("Name = " + name); System.out.println("Population = " + population); System.out.println("Growth rate = " + growthRate + "%"); } /** Precondition: years is a nonnegative number. Returns the projected population of the calling object after the specified number of years. */ public int projectedPopulation(int years) { double populationAmount = population; int count = years; while ((count > 0) && (populationAmount > 0)) { populationAmount = (populationAmount + (growthRate/100) * populationAmount); count--; } if (populationAmount > 0) return (int)populationAmount; else return 0; }}
Example using a toString Method (cont’d) public void set(String newName, int newPopulation, double newGrowthRate) { name = newName; if (newPopulation >= 0) population = newPopulation; else { System.out.println("ERROR: using a negative population."); System.exit(0); } growthRate = newGrowthRate; } public String getName( ) { return name; } public int getPopulation( ) { return population; } public double getGrowthRate( ) { return growthRate; } public boolean equals(Species otherObject) { return ((name.equalsIgnoreCase(otherObject.name)) && (population == otherObject.population) && (growthRate == otherObject.growthRate)); }
Text-File Input with BufferedReader • The class BufferedReader is the preferred stream class for reading from a text file. • To open a file for reading use the statement: BufferedReader Stream_Name = new BufferedReader(new FileReader(File_Name)); • If your program attempts to open a file for reading, but there is no such file, then a FileNotFoundException is thrown
Text-File Input with BufferedReader (cont’d) • BufferedReader has no methods that, like nextInt, can read a number. • The only way that you can use the class BufferedReader to read a number from a text file is to read it as a string and then convert the string to a number. • The class BufferedReader does have a method, named simply read, that will read a single character, however, it read it as an integer. To get the character you should write: char next = (char)(inputStream.read());
Example Using the Class BufferedReader import java.io.*;public class TextFileInputDemo{ public static void main(String[] args) { try { BufferedReader inputStream = new BufferedReader(new FileReader("data.txt")); String line = null; line = inputStream.readLine( ); System.out.println("The first line in data.txt is:"); System.out.println(line); line = inputStream.readLine( ); System.out.println("The second line in data.txt is:"); System.out.println(line); inputStream.close( ); } catch(FileNotFoundException e) { System.out.println("File data.txt was not found"); System.out.println("or could not be opened."); } catch(IOException e) { System.out.println("Error reading from file data.txt."); } }}
Reading a File Name from the Keyboard import java.io.*;import java.util.*;public class TextFileInputDemo2{ public static void main(String[] args) { System.out.println("Enter file name:"); Scanner keyboard = new Scanner(System.in); String fileName = keyboard.next( ); try { 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); line = inputStream.readLine( ); System.out.println("The second line in " + fileName + " is:"); System.out.println(line); inputStream.close( ); } catch(FileNotFoundException e) { System.out.println("File " + fileName + " not found."); } catch(IOException e) { System.out.println("Error reading from file " + fileName); } }}