I really don’t know, why this is so complex and hard just for reading a file with a lot of classes
- InputStream
- DataInputStream
- InputStream
- BufferReader
What are advantages of below? And what are philosophy at here?
private static String fileToString(String filename) throws IOException
{
InputStream resourceAsStream;
resourceAsStream = "".getClass().getResourceAsStream(filename);
DataInputStream in = new DataInputStream(resourceAsStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
String line;
// For every line in the file, append it to the string builder
while((line = reader.readLine()) != null)
{
builder.append(line);
}
return builder.toString();
}
The philosophy is one of flexibility. Using different types of data streams, you can easily read and write different types of data, like bytes, lines of text, or entire user-defined objects, one at a time to and from I/O sources.
From The Java Tutorials – I/O Streams:
Start at the lesson trail Lesson: Basic I/O to get a good overview of Java I/O.
If you want to see concrete examples of how to simplify I/O for various data types in Java, I recommend having a look at the In.java and Out.java classes from Sedgewick & Wayne’s standard libraries.