patternjavaMinor
Reading a file into string in Java
Viewed 0 times
readingfileintojavastring
Problem
I am quite new to Java, and I am trying to read a file into a string (or should I use byte arrays for this?). File can be anything, such as a text file or executable file etc. I will compress what I read and write it to another file.
I am thinking of using this code:
Does this look good to you? I was reading "Reading and writing text files" and I was a little bit confused over all the different ways one can use to read files.
I am thinking of using this code:
public static String readFile(File f) {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
} catch (IOException e) {
System.err.println("I/O Exception:" + e.getMessage());
return null;
}
return sb.toString();
}Does this look good to you? I was reading "Reading and writing text files" and I was a little bit confused over all the different ways one can use to read files.
Solution
Why reinvent the wheel?
Use commons-io's
Use commons-io's
FileUtils.readFileToByteArray(File)(javadoc)Context
StackExchange Code Review Q#29521, answer score: 2
Revisions (0)
No revisions yet.