I really don't know, why this is so complex and hard just for reading a file with a lot of classes
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();
}
If you want to read a file for which you have a path, you can even go for this:
List<String> lines = Files.readAllLines(Paths.get("/path/to/your/file"), charset);
Note: Java 7+ required
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:
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With