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.
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.
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); }