Old question, two new answers so far each with some concerns....
Firstly, the original code has a significant bug, which should be pointed out:
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
The above code will read a line from the BufferedReader
but it will strip the end-of-line marker (whether that is \r\n
, \n
, or whatever). When you append this value to the StringBuilder
you lose this data.
Unless there is a general need for importing third-party libraries, I try to avoid them. In this case, while the apache commons may have a convenience function, I would hesitate to create a dependency on it for just this function.
Anyway, this particular commons call has a new-in-java7 analogue: byte[] Files.readAllBytes(Path);
Similarly, the OP's actual situation may be solvable by: String[] Files.readAllLines(Path, Charset);
If neither of the above methods will solve the OP's situation, then I would recommend a more traditional approach.....
If you want the data as a byte[] array, then use an Stream approach, but if you want the file as a String, use a Reader, and then:
// guess the amount of characters to be about half the number
// of bytes in the file. It will be something more than this, but
// this will be enough to limit the number of memory re-allocations.
final int charguess = f.length() > Integer.MAX_VALUE
? Integer.MAX_VALUE // will likely throw OutOfMemory, not our fault...
: ((int)(f.length() + 2) / 2 );
final StringBuilder sb = new StringBuilder(charquess);
final char[] buffer = new char[f.length() > 4096 ? 4096 : (int)f.length() + 1];
try (FileReader reader = new FileReader(f)) {
int len = 0;
while ((len = reader.read(buffer)) > 0) {
sb.write(buffer, 0, len);
}
return sb.toString();
}
For more robust solutions I recommend specifying the charset encoding that you require the file to be in, and using an InputStream with an InputStreamReader to get the encoding right.
EDIT: Finally, none of the answers so far (including mine, until now) have addressed the OP's actual anticipated usage. He wants to compress the file. The logical solution for this would be a CompressedOutputStream, and a byte[] based InputStream
File outfile = new File(f.getPath() + ".gz");
try (FileInputStream fis = new FileInputStream(f);
GZipOutputStream gzos = new GZipOutputStream(new FileOutputStream(outfile))) {
byte[] buffer = new byte[4096];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
gzos.write(buffer, 0, len);
}
gzos.finish();
}