Anonymous Person
Anonymous Person

Reputation: 219

Reading data in Java

What's the difference between using a BufferedReader and a BufferedInputStream?

Upvotes: 1

Views: 746

Answers (3)

Mike Thomsen
Mike Thomsen

Reputation: 37526

As the names imply, one is for reading data, and the other is for outputting data.

Upvotes: 1

Adamski
Adamski

Reputation: 54725

A BufferedReader is used for reading character data. A BufferedOutputStream is used for writing binary data.

Any classes inheriting from Reader or Writer deal with 16-bit unicode character data, whereas classes inherting from InputStream or OutputStream are concerned with processing binary data. The classes InputStreamReader and OutputStreamWriter can be used to bridge between the two classes of data.

Upvotes: 4

Kayser
Kayser

Reputation: 6704

Bufferedreader reads data from a file as a string. BufferedOutputStream writes to a file in bytes. BufferedInputStream reads data in bytes
Sample to Bufferedreader:

try {
       BufferedReader br = new BufferedReader(new FileReader(new File(your_file));
       while ((thisLine = br.readLine()) != null) { 
         System.out.println(thisLine);
       }
     } 

Sample to BufferedOutputStream:

//Construct the BufferedOutputStream object
        bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));

        //Start writing to the output stream
        bufferedOutput.write("Line 1".getBytes());
        bufferedOutput.write("\r\n".getBytes());
        bufferedOutput.write("Line 2".getBytes());
        bufferedOutput.write("\r\n".getBytes());

Bufferedinputstream reads in byte:
Sample :

 //Construct the BufferedInputStream object
        bufferedInput = new BufferedInputStream(new FileInputStream(filename));

        int bytesRead = 0;


        while ((bytesRead = bufferedInput.read(buffer)) != -1) {                

            String chunk = new String(buffer, 0, bytesRead);
            System.out.print(chunk);
        }

Upvotes: 3

Related Questions