Local

..:: Home
..:: Legal
..:: Contact
..:: About
..:: RSS
..:: Log in

Links

..:: Fake Bill Gates
..:: Tap the Hive

A Random Quote

"The existence of piratable copies tells a publisher that their DRM is not strict enough. The popularity of piratable copies tells a publisher that people like the content, but don't like the publisher."

File Input/Output in Java: FileIO.java

I also wrote this little object back in undergrad to help fix up the read/writing of files.

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;

//creating a buffer every time you want to read or write a file can get quite
//tedious. what my class does is read a file and return the file as an
//objectlist based on linebreaks.  it's not incredible code efficiency, but
//it definitely shows benefits of oo.
public class FileIO
{
  //Attributes

  //Constructors
  public FileIO()
  {
       //basic constructor
  }

  //Functions
  public ObjectList read(String fileName)
  {
    //reads file, returning it as an ObjectList where each element is separated
    //by a newline character
    ObjectList list = new ObjectList();
    System.out.println("Reading file: " + fileName);
    try
    {
      FileReader fr = new FileReader(fileName);
      BufferedReader br = new BufferedReader(fr);
      String line;
      while ((line = br.readLine()) != null)
      {
        list.add(line);
      }
      return list;
    }
    catch (Exception e)
    {
      System.out.println("Can't read file: " + fileName);
      return null;
    }
  }

  public void write(String fileName, String toWrite)
  {
    //writes a single string to a file
    try
    {
      File outputFile = new File(fileName);
      FileWriter out = new FileWriter(outputFile);
      out.write(toWrite);
      out.close();
    }
    catch (Exception e)
    {
      System.out.println("Can't write to " + fileName + ": " + e.toString());
    }
  }

  public void write(String fileName, ObjectList toWrite)
  {
    //writes an ObjectList to a file separating each element by linebreaks
    System.out.println("Writing to " + fileName);
    try
    {
      File outputFile = new File(fileName);
      FileWriter out = new FileWriter(outputFile);

      int i = 0;
      while(toWrite.peek(i) != null)
      {
        out.write(toWrite.peek(i) + "n");
        i++;
      }
      out.close();
    }
    catch (Exception e)
    {
      System.out.println("Can't write to " + fileName + ": " + e.toString());
    }
  }

  public static void main(String[] args)
  {
    //example code use
    FileIO fileio = new FileIO();
    ObjectList list = fileio.read(”djlosch/FileIO.java”);
    fileio.write(”djlosch/FileIO.txt”, list);
  }
}

Leave a Reply