0% found this document useful (0 votes)
55 views

JavaFileIO PDF

This document discusses how to read from and write to files in Java. It shows how to open a file for reading using a BufferedReader and FileReader, read lines from the file, and convert the lines to other data types like integers and doubles. It also demonstrates opening a file for writing using a PrintWriter and FileWriter, writing lines to the file, and wrapping file I/O in try/catch blocks to handle exceptions.

Uploaded by

Doruk Korkmaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

JavaFileIO PDF

This document discusses how to read from and write to files in Java. It shows how to open a file for reading using a BufferedReader and FileReader, read lines from the file, and convert the lines to other data types like integers and doubles. It also demonstrates opening a file for writing using a PrintWriter and FileWriter, writing lines to the file, and wrapping file I/O in try/catch blocks to handle exceptions.

Uploaded by

Doruk Korkmaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Java File I/O

// Opening a file for reading:


BufferedReader rd = new BufferedReader(new FileReader(fileName));
// rd.readLine() returns next line or null at the end of file
String line = rd.readLine();
// What about readInt, readDouble, etc.
int i = Integer.parseInt(line);
double d = Double.parseDouble(line);
// Opening a file for writing:
PrintWriter wr = new PrintWriter(new FileWriter(fileName));
// FileWriter overwrites existing files by default, use this to append:
PrintWriter wr = new PrintWriter(new FileWriter(fileName, true));
// wr.println() writes a line to the file:
wr.println(line);
// Need to wrap file i/o code with try/catch:
try {
BufferedReader rd = new BufferedReader(new FileReader(filename));
while (true) {
String line = rd.readLine();
if (line == null) break;
// Do something with line here...
}
rd.close();
} catch (IOException ex) {
println(Got error: + ex);
}

You might also like