Skip to content

Instantly share code, notes, and snippets.

@hawx
Created March 30, 2012 17:34
Show Gist options
  • Save hawx/2253214 to your computer and use it in GitHub Desktop.
Save hawx/2253214 to your computer and use it in GitHub Desktop.
It's like the people who designed java didn't imagine reading files would be a common task...

SimpleIO

Really who, WHO? designed java. It's so verbose it makes [something verbose] look simple. The designers must have been in a meeting, I guess this can only be the product of a TON of meetings, and they were all like here's an idea "let's make common tasks simple", and some other guy (probably middle-aged, balding with a harley said "yeah, like reading and writing to files". And then everyone in the room gave him the death stare, Dr Cooper style, and one guy just said "what, who needs to do that?". Everyone in the room just nodded like sheep.

Anyway this class makes life easier, less java-like if you will:

String contents = SimpleIO.read("my-file");                                           
SimpleIO.write("another-file","hey look, this is a one-liner");                       

Enjoy.


Oh also I used a String; everyone seems to use StringBuilders and/or get's annoyed when people build Strings like this. The clue is supposedly in the title, StringBuilder is for building Strings. But nobody and I mean nobody can explain why StringBuilder is better. So I used a String in #read.

import java.io.*;
public class SimpleIO {
public static String read(String path) {
String s = "";
try {
BufferedReader in = new BufferedReader(new FileReader(path));
try {
String line = null;
while ((line = in.readLine()) != null) {
s += line + "\n";
}
} finally {
in.close();
}
} catch (IOException e) {
// something?
}
return s;
}
public static void write(String path, String stuff) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(path));
try {
out.write(stuff);
} finally {
out.close();
}
} catch (IOException e) {
// something?
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment