Skip to content

Instantly share code, notes, and snippets.

@roopeshvaddepally
Created March 15, 2012 20:15
Show Gist options
  • Save roopeshvaddepally/2046616 to your computer and use it in GitHub Desktop.
Save roopeshvaddepally/2046616 to your computer and use it in GitHub Desktop.
Read a file as string (open(filename).read() in python)
public static String readFileAsString(String fileName) throws java.io.IOException {
java.io.InputStream is = new java.io.FileInputStream(fileName);
try {
final int bufsize = 4096;
int available = is.available();
byte data[] = new byte[available < bufsize ? bufsize : available];
int used = 0;
while (true) {
if (data.length - used < bufsize) {
byte newData[] = new byte[data.length << 1];
System.arraycopy(data, 0, newData, 0, used);
data = newData;
}
int got = is.read(data, used, data.length - used);
if (got <= 0)
break;
used += got;
}
return new String(data, 0, used);
} finally {
is.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment