User Tools

Site Tools


cs257:reading_files_i

There are several approaches to reading files in Java; at least two are described in the CS 157 text, Java: An Eventful Approach. The code snippets below illustrate using the BufferedReader class for reading from a file, and BufferedWriter for writing to a file.

The trick, as with any code involving I/O, is to get the exception handling right.

import java.io.*;
private static BufferedReader reader;
String file;  // holds input filename
 
// ...
 
 try {
    reader = new BufferedReader (new FileReader(file));
 } catch(IOException e) {
     System.out.print(e);
 }
 
// if it worked, we know we can read things, for example, the first line from the file
String line;
 
 try {
     line=reader.readLine();
 } catch (IOException e) {
     System.out.print(e);
 }
 
// done? close it
 reader.close();
 
/*------------------------------------------------------*/
 
// Now to write to a file
 
 try { 
     writer = new BufferedWriter(new FileWriter(file));
 } catch (IOException e) {
    // deal with it somehow...
 }
 
 String msg = "data to store in the file";
 
 try { 
    writer.write(msg, 0, msg.length());
    // if at end of line
    writer.newLine();
 } catch (IOException) {
   // deal with it somehow...
 }
 
 // done? always close the file
 writer.close();
cs257/reading_files_i.txt · Last modified: 2015/08/31 08:53 by scarl