lördag 19 november 2011

Java - Reading a text file to a String

Often when you need to read a complete file you use a BufferedReader and read each line of the file until you have read all the lines in the file. This operation can simple be performed using a DataInputStream instead.

File file = new File("FILE YOU LIKE TO READ.");
DataInputStream inputStream = null;
try {
  byte[] bytes = new byte[(int) file.length()];
  inputStream = new DataInputStream(new FileInputStream(file));
  inputStream.readFully(bytes);
  return new String(bytes);
} finally {
  if (inputStream != null) {
    inputStream.close();
  }
}

Of course this require you to know how large the file is that you like to read. It will not work on a arbitrary stream. Also if you are using Java7 the try/finally can be omitted, YEJ!

Inga kommentarer:

Skicka en kommentar