Transcript CHAPTER 1

Two Ways to Store Data in a File
• Text format
• Binary format
Text Format
Information stored as a sequence of characters
Characters are stored as their ASCII equivalent
- int value 12345 stored as ‘1’ ‘2’ ‘3’ ‘4’ ‘5’
5 bytes
91 92 93 94 95
File is ‘readable’ by humans.
Java classes ‘Reader’ and ‘Writer’ (and their
subclasses) are for use with text files
Binary Format
More compact and efficient
int 12345 stored using binary representation:
00000000 00000000 0010000 0011100
00
00
48
57
4 bytes
Java classes InputStream and OutputStream
(and their subclasses) exist to read and write these
types of files
To Read Text Data From a Disk File
• Create a FileReader object
• Use its read method to read a single character
o returns the next char as an int
o or the integer -1 at end of input
• Test for -1 to determine if a char was read
• Close the file when done
Code
FileReader reader = new
FileReader("input.txt");
int next = reader.read() ;
char c;
if (next != -1)
c = (char)next();
.
.
reader.close().
Write a Character to Disk
FileWriter writer = new
FileWriter("output.txt");
char c =‘a';
writer.write(c);
writer.close();
Reading Text Line by Line
Create a BufferedReader object (pass a
FileReader object to constructor)
objects of type BufferedReader can
group characters – ‘buffer’ them
method readLine() available, to provide file data 1 line at a
time (the method handles reading the characters from
the FileReader for you)
readLine() returns the next line of file (as a String), or null
if none exists
//Reads first line from file named input.txt
// line is expected to contain a double value
FileReader reader = new FileReader("input.txt");
BufferedReader in = new BufferedReader(reader);
String inputLine = in.readLine();
double x = Double.parseDouble(inputLine);
//Reads and all lines from file
// and writes them to console
import java.io;
public class demo{
public static void main(String[] args)throws IOException{
FileReader reader = new FileReader("input.txt");
BufferedReader in = new BufferedReader(reader);
String line = in.readLine();
While (line != null){
System.out.println(line);
line = in.readLine();
}
in.close();
}
}
Writing Strings to Text Files
A PrintWriter object handlethe ‘unbuffering’
of data for output file writer
Create PrintWriter object
(pass FileWriter
object to constructor)
PrintWriter class provides ‘println’ method
which accepts data and prints the String form
(which it provids to FileWriter one char at a
time)
FileWriter writer = new FileWriter(“output.txt”)
PrintWriter out = new PrintWriter(writer);
//use PrintWriter object to output data to file output.txt
FileWriter writer = new FileWriter(“output.txt”)
PrintWriter out = new PrintWriter(writer);
out.println(29.95);
out.println(new Rectangle(5,10,15,25));
out.println("Hello, World!");