Course List: http://www.c-jump.com/bcc/
Class java.io.BufferedWriter extends the java.io.Writer class.
BufferedWriter implements buffered output of character streams
java.io.PrintWriter adds character formatting for primitive types and Strings
FileWriter implements low-level writing of character files
import java.io.*; import java.nio.file.*; public class TextOutputDemo { public static void main(String[] args) { // Get a Path object for the file Path booksPath = Paths.get( "C:/myfiles/dummy.txt" ); File booksFile = booksPath.toFile(); //Write data to the file try { PrintWriter outp = new PrintWriter( // output formatting functionality new BufferedWriter( // implements stream buffer for character output new FileWriter(booksFile))); // basic writing of character files // character output: outp.println("book\tBeginning Java Programming\t49.50"); outp.close(); } catch (IOException e) { System.out.println(e); } } }//class TextOutputDemo
Note that File objects are not files! The File class keeps metadata describing either file or directory, useful when working with files and directories of the file system.
|
|
Code that appends a string and an object to a text file:
// open an output stream for appending to the text file PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter("log.txt", true))); // write a string and an object to the file out.print("This application was run on "); Date today = new Date(); out.println(today); // flush data to the file and close the output stream out.close();
Code that writes a Book object to a delimited text file
// open an output stream for overwriting a text file PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter(booksFile))); // write the Book object to the file out.print(book.getCode() + "\t"); out.print(book.getDescription() + "\t"); out.println(book.getPrice()); // flush data to the file and close the output stream out.close();
The classes designed for processing plain text files:
Class java.io.BufferedReader
extends java.io.Reader class
implements character-based input stream
BufferedReader implements buffered reading from a character stream
import java.io.*; import java.nio.file.*; try ( BufferedReader in = new BufferedReader( // implements buffered reading new FileReader(booksFile) ) ) // implements reading character files { String line = in.readLine(); /// Read a line of text System.out.println(line); } catch (IOException e) { System.out.println(e); }
abstract Reader
Constructors of the classes in the Reader hierarchy
Constructor Throws ---------------------------- -------------------- BufferedReader(Reader) None FileReader(File) FileNotFoundException FileReader(StringPathName) FileNotFoundException
Classes for opening a character file for buffered reading:
BufferedReader implements buffered reading from character stream FileReader implements low-level input from character files
Attaching a character input stream to a file
// implements buffered reading from a character stream BufferedReader in = new BufferedReader( // implements reading character files new FileReader("books.txt"));
Implements buffered reading from a character stream
Common methods of the BufferedReader class and exceptions thrown:
Method Throws --------------- -------------------- readLine() IOException read() IOException skip(longValue) IOException close() IOException
Code that reads the records in a text file
// implements buffered reading from a character stream BufferedReader in = new BufferedReader( // implements reading character files new FileReader("books.txt")); // read the records of the file String line = in.readLine(); while(line != null) { System.out.println(line); line = in.readLine(); } // close the input stream in.close();
Code that reads a Book object from a delimited text file
// implements buffered reading from a character stream BufferedReader in = new BufferedReader( // implements reading character files new FileReader("books.txt")); // read the next line of the file String line = in.readLine(); // parse the line into its columns String[] columns = line.split("\t"); String code = columns[0]; String description = columns[1]; String price = columns[2]; // create a book object from the data in the columns Book p = new Book( code, description, Double.parseDouble(price)); // print the Book object System.out.println(p); // close the input stream in.close();
Sample output for code that reads a Book object from a delimited text file
Code: book Description: Beginning Java Programming Price: $49.50
The Scanner class can be used for formatted input from a character file:
Scanner inFile = new Scanner( new FileReader( "myfile.dat" ) );
To input data, call next(), nextInt(), nextDouble(), and so on:
String firstName; String lastName; double hoursWorked; double payRate; double wages; firstName = inFile.next(); lastName = inFile.next(); hoursWorked = inFile.nextDouble(); payRate = inFile.nextDouble(); wages = hoursWorked * payRate; inFile.close(); //close the input file
IOException EOFException FileNotFoundException
Common I/O exceptions:
IOException // any I/O exception EOFException // attempt to read beyond the end of file FileNotFoundException // file does not exist
Path booksPath = Paths.get("books.txt"); if (Files.exists(booksPath)) { File booksFile = booksPath.toFile(); try (BufferedReader in = new BufferedReader( // implements buffered reading from a character stream new FileReader(booksFile))) // implements reading character files { String line = in.readLine(); while(line != null) { System.out.println(line); line = in.readLine(); } } catch (IOException e) { System.out.println(e); } } else { System.out.println( booksPath.toAbsolutePath() + " doesn't exist"); }
abstract Writer
BufferedWriter PrintWriter OutputStreamWriter FileWriter
Classes for opening a character file for buffered writing:
PrintWriter contains methods for formatting data to a text stream BufferedWriter implements stream buffer for character output FileWriter basic writing of character files
Constructors of the classes in the Writer hierarchy:
Constructor Throws ----------------------------------------- ------------ PrintWriter(Writer[, booleanFlush]) None BufferedWriter(Writer) None FileWriter(File[, booleanAppend]) IOException FileWriter(StringPathName[, booleanAppend]) IOException
Opening a file without a buffer (not recommended)
FileWriter fileWriter = new FileWriter("books.txt"); PrintWriter out = new PrintWriter(fileWriter);
A more concise way to code this example would be
PrintWriter out = new PrintWriter( new FileWriter("books.txt"));
Opening a file with a buffer
PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter("books.txt"));
Opening a file for an append operation
PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter("books.txt", true)));
Opening with autoflush feature turned on
PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter("books.txt")), true);
Note: Closing the output file is important:
out.close();
close() ensures that the buffer holding the output will be emptied -- all output generated by the program is sent to the output file.
Class java.io.BufferedWriter is a counterpart to BufferedReader:
extends the java.io.Writer class
implements buffered output of character streams
writes text to an output stream, buffering the characters
overloads write() methods for writing characters, arrays, and strings
Abstract class OutputStream represents an output stream of bytes
Class java.io.BufferedOutputStream implements a buffered output stream of bytes
Class java.io.OutputStreamWriter
is a bridge from character streams to byte streams
characters written to it are encoded into bytes using a specified character set
// Writes employee data into ASCII text file sequentially, in a loop import java.nio.file.*; import java.io.*; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; public class WriteEmployeeFile { public static void main(String[] args) { Scanner input = new Scanner(System.in); Path file = Paths.get("C:\\example\\Employees.txt"); String s = ""; String delimiter = ","; int id; String name; double payRate; final int QUIT = 999; try { OutputStream output = new // using java.nio.file.StandardOpenOption.CREATE // BufferedOutputStream implements a buffered output stream BufferedOutputStream(Files.newOutputStream(file, CREATE)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); System.out.print("Enter employee ID number >> "); id = input.nextInt(); while(id != QUIT) { System.out.print("Enter name for employee #" + id + " >> "); input.nextLine(); name = input.nextLine(); System.out.print("Enter pay rate >> "); payRate = input.nextDouble(); s = id + delimiter + name + delimiter + payRate; writer.write(s, 0, s.length()); writer.newLine(); System.out.print("Enter next ID number or " + QUIT + " to quit >> "); id = input.nextInt(); } writer.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }//class WriteEmployeeFile
Class BufferedInputStream implements input stream of bytes
Class InputStreamReader
is a bridge from byte streams to character streams
reads bytes and decodes them into characters using a specified character set
for efficiency it is wrapped within BufferedReader.
// Reads employee data from ASCII text file sequentially, line by line import java.nio.file.*; import java.io.*; public class ReadEmployeeFile { public static void main(String[] args) { Path file = Paths.get("C:\\example\\Employees.txt"); String s = ""; try { InputStream input = new BufferedInputStream(Files.newInputStream(file)); // BufferedReader implements reading character files BufferedReader reader = new BufferedReader(new InputStreamReader(input)); // uses the default charset s = reader.readLine(); while(s != null) { System.out.println(s); s = reader.readLine(); } reader.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }//class ReadEmployeeFile