Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java implements so hard to reading a file [closed]

Tags:

java

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();
}
like image 486
vietean Avatar asked Aug 24 '12 16:08

vietean


2 Answers

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

like image 107
assylias Avatar answered Nov 11 '22 20:11

assylias


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.

like image 20
Bill the Lizard Avatar answered Nov 11 '22 21:11

Bill the Lizard