Search code examples
javaeclipsebufferedreaderfilereaderwriter

How does the BufferedReader know which file to read?


Lets say I have

try (FileWriter fw = new FileWriter("test.txt",false)) {
    BufferedReader bw=new BufferedReader(new InputStreamReader(System.in));
    do {
        str = bw.readLine();
        if (str.compareTo("stop") == 0) break;
        str = str + " ";
        fw.write(str);
    } while(str.compareTo("stop")!=0);
} catch(IOException e) {

}

How does my BufferedReader know the input stream to read? In the case of bw.readLine()? Also in the case of my FileReader? Why is it then that I have to specify which file to read from? Or is it

String s;
//create a BufferedReader that reads a stream of characters
//FileReader Writes character Values 
try (FileReader decodeFile = new FileReader("test.txt")) {
    BufferedReader readFile=new BufferedReader(decodeFile);

    //first check to see if br has a null value
    while ((s=readFile.readLine()) != null) {
        System.out.println(s);
    }
} catch (IOException e) {
    e.printStackTrace();
}

I am very confused about this can someone please shed some light on this? And yes I have read the documentation so I am aware of what both do


Solution

  • Streams are simply a continuous flow of data coming in. Most Reader class subclasses in Java declare where the stream comes from in the constructor.

    1. For the first case, the InputStreamReader gets its input from System.in. System.in is the stream of data which is provided by the user input. Try running the java file and type a few characters and press enter at the terminal.

    2. BufferedReader is a reader specialized in reading text efficiently. It gets the contents of the data from another stream source. In this case, the BufferedReader(decodeFile) signifies decodefile is where the BufferedReader reads stream data from. decodefile is a FileReader type, and FileReader("test.txt") signifies the file read is from a file called test.txt. Hence, the flow would go like this: "test.txt" -> FileReader -> BufferedReader

    Updated

    Looking at the documentation helps. https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html

    PrintWriter helps write your output in a format you would like. (By format, I mean appending a character, line flushing, formatting in general.)

    On the other hand, a FileWriter writes stream contents to a file. Hence in this scenario, the following would would be the flow.

    String -> PrintWriter -> FileWriter -> "outputfile.txt"

    The string content could change like the following

    "text" -> "formatted text" -> "for", "matted ", "text" -> "formatted text"

    The whole point of using streams is to chunk large amounts of data so that the process doesn't take up too much RAM (memory). Hence, chunking might (but not necessarily) happen as illustrated above.