Java Notes

BufferedReader/Writer

BufferedReader and BufferedWriter methods

java.io.BufferedReader and java.io.BufferedWriter are used to read/write Strings from/to text files. Assume

BufferedReader br;
BufferedWriter bw;
File f;
char[] ca;
String s;
int c;         // This is an int to hold either a char or -1.
int offset, len, size;

BufferedReader

BufferedReader Constructor -- see examples
br = new BufferedReader(new FileReader(f));
BufferedReader Methods
s = br.readLine() Returns next input line without newline char(s) or null if no more input. May throw IOException.
c = br.read() Reads and returns one char. Returns -1 on end-of-file. Note that that this returns an int, which is necessary so that the -1 value indicating EOF can be stored. The int value can be cast to a char. May throw IOException.
size = br.read(ca, offset, len) Read up to len chars into ca starting at index offset. Returns -1 on end-of-file. May throw IOException.
 br.close() Close when finished reading to unlock file.

BufferedWriter

BufferedWriter Constructor -- see examples
bw = new BufferedWriter(new FileWriter(f));
BufferedWriter Methods
bw.write(s, offset, len) Writes len chars from s starting at index offset. May throw IOException.
bw.write(ca, offset, len) Writes len chars from ca starting at index offset. May throw IOException.
bw.write(s) Writes s to file. Doesn't add newline char. May throw IOException.
bw.write(c) Writes single character c to file. May throw IOException.
bw.newLine() Writes operating-system dependent newline (CR, LF, or CRLF).
bw.close() Call close() when finished writing, otherwise data may not be written to disk.

Example

See File I/O - Text Files for an example of reading and writing text files.