Skip to content

Instantly share code, notes, and snippets.

@colin-haber
Created February 2, 2012 19:38
Show Gist options
  • Select an option

  • Save colin-haber/1725315 to your computer and use it in GitHub Desktop.

Select an option

Save colin-haber/1725315 to your computer and use it in GitHub Desktop.
Sample simple File IO
package com.n1nja.fileio;
import java.io.*;
public class FileLoader {
public static void main(String[] args) {
new FileLoader(args);
}
//The file to read
private final File f = new File("rpsls.rps");
private BufferedReader in;
private FileLoader(String...r) {
//Try the contained code. If it throws an exception, break. This is
//just standard Java exception handling.
try {
//Build a new reader around the file. It requires two levels because
//the BufferedReader provides handy convienience methods like
//readLine() that FileReader does not.
in = new BufferedReader(new FileReader(f));
String s = null;
do {
s = in.readLine();
//readLine() returns null if there are no more lines, so check
//that. Also, skip it if the line's first display character is
//a '#'.
if (s != null && !s.trim().substring(0, 1).equals("#")) {
//If it passes both checks, print it to stdout.
System.out.println(s);
}
} while (s != null);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
# Hashes mark comments and are ignored by the parser.
# You can probably figure out the format.
rock:
crushes:scissors
crushes:lizard
paper:
covers:rock
disproves:Spock
scissors:
cut:paper
stab:lizard
lizard:
poisons:Spock
eats:paper
Spock:
smashes:scissors
vaporises:rock
# Simple enough.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment