Files that Make You Smile

Files.  Those floppy, large things full of paper that used to be the bane of office workers are now electronic.  No more lifting stacks of paper and having a couple of papers fall on the floor and get out of order!  Instead we have to keep even more files in order inside folders, inside other folders on our computers.  Not surprisingly, we have programs that can read and write files so we don’t have to do everything manually.

Overall, file reading is a simple process.  Write a program that opens it up, scans through it, does something with the information, and closes it.  File writing is about the same but slightly trickier because we have to read and store the original information, then print out all the information, old and new.  Warning:  if you are trying to open a file to both read and print at the same time it won’t work.  Only one operation can check it out at any given time.  Let’s get started:

Read File – Read me a story –  please!

To read the contents of a file, we must know the filename, which we take in as a parameter.  We then create a new empty string to store the file contents.  

public String readFile(String filename) {
  String input = "";
  try(Scanner scan = new Scanner(new File(filename))) {
    while(scan.hasNext()) {
      input += scan.nextLine() + "\n";
    }
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
  return input;
}

 

Next comes the try-catch block.  Here, we use “try with resources”, a mechanism where we declare a Scanner object and Java takes care of safely opening and closing it.  Be careful!  If you miss the “new File” part of this, the Scanner will think it’s supposed to be reading some unknown thing called filename.  Are these real files?  Yes, and no.  The File object that Java knows is a virtual representation of your file stored on the computer that lets it access it through a Scanner or PrintWriter.  Remember, you cannot just read a File object on its own!

Once we have the Scanner opened up, we enter a while-loop that keeps on reading the file until the end, adding the next line to the input string each time it iterates.  We also add “\n” the new line character to preserve the line breaks.

Try it – but be ready to catch an exception

The catch section of the try-catch block says what to do if an exception is thrown.  A FileNotFoundException is caused by the absence of the specified file or a read/write permission.  Often, this exception means your file is in the wrong place, or you misspelled it’s name.  This exception will print a message like this to your console:

All this red ink says “Sorry, we can’t find the file you told us to look for” and gives you the stack trace, or series of commands, where things went wrong.  One common error is having the file in the wrong folder, to trying to access a file in another folder without providing its absolute classpath. 

An absolute class path is the full address of the file and might look like:  C:\Users\Me\Desktop\MyJavaIdeas\ProjectFiles\TradCaesarCipherOrig.txt        You can kind of imagine it as giving directions to a Martian so they can get to the White House:  PlanetEarth\NorthAmerica\ UnitedStates\Washington, D.C.\1600PennsylvaniaAve.  Basically, each program only knows its own file, so if it needs something from somewhere else, you have to give it the map to get there.  Finally, we return the contents of the file as the string.

Print File – Print out those words

public void printFile(String fileOutput, String filename) {
  try(PrintWriter print = new PrintWriter(new File(filename))) {
    print.print(fileOutput);
    System.out.println(fileOutput);
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
}

 

This looks a lot like ReadFile, except it prints a file out using a PrintWriter.  The try-with-resources is about the same:  you declare and initialize the PrintWriter with a new File object, and Java does the opening, closing, and general cleanup.  The PrintWriter is a bit more forgiving than the Scanner, and will still figure out what to do if you omit the new File and just give it the filename.  Here, we print out to both the file and the console.  As with the Scanner, we use the catch part of the block to catch problems, typically if a write permission is denied.

Note:  when specifying the filenames for Scanner and PrintWriter, you must include the file extension.  A few common ones are .txt, , .in, .out, and .csv.  Please note that Scanners and PrintWriters work with open-source format files, but you will get an error if you try to read or write a .docx file.

That’s about it.  Try out the code, making sure the file you’re trying to read exists and is where you tell the scanner to look.

Download the Java file here:  SimpleFileIO.java , and view the text version in your browser here:  SimpleFileIO.txt

Two sample text files to copy between are Stevenson.txt and StevensonCopy.txt