# BufferInputStream



## Caliraj (Mar 22, 2006)

Hi,
I was going through a program to illustrate the use of BufferedInputStream.The program is as below:
import java.io.*;
class printfile
{
public static void main(String args[]) throws IOException
{
try
{
FileInputStream fin=new FileInputStream("hello.java");
BufferedInputStream b=new BufferedInputStream(fin);
int ch=0;
while((ch=b.read())>-1)
{
StringBuffer buf=new StringBuffer();
buf.append((char)ch);
System.out.print(buf.toString());
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Now, this is a program to print the particular chosen file in the dos prompt(If im right )
Now Im unable to reason out why -1 is present in the "while loop"....I tried replacing -1 with 5,7....the output was same....Then i thought may be its for the caharacter count....so the first line(class hello) occupies 11 columns.....I replaced -1 with 11 expecting the output as the same except that the first line would be omitted.....but the output was only the line!!!!
I was also told that -1 is used instead of null....so when i replaced the expression as 
while((ch=b.read())!=null), it gave me an error.
COuld you help me out?
Thanks,
Cali


----------



## IMM (Feb 1, 2002)

The read method returns -1 if the end of the stream has been reached.


----------



## Caliraj (Mar 22, 2006)

Hi,
Thanks for the reply.But Im unable to understand why it gives the 1st line only as output if i replace -1 with 11. COuld you explain the logic?
Thanks, 
Cali


----------



## IMM (Feb 1, 2002)

I haven't see your input file - but I'll guess that it is text.
As you work through that input file - b becomes the character read. (or int == -1 if no char available)
If this is a text file, the likelihood of encountering a 'character' less than 9 is remote (9 is the tab character) - but you are almost certain to encounter the characters representing the end of a line.
The Linefeed char (LF) at the end of a line is 10 (0x0A as hex) and the Carriage Return Character (CR) which may be at the end of a line is 13 (0x0D).
Your test for > 11 (to continue) will fail when you encounter the LF char at the end of the first line.


----------



## Chicon (Jul 29, 2004)

FileInputStream and BufferedInputStream are mainly used to read binary files.
To read a file like "Hello.java" which may be considered as a text file, the appropriate classes are :
FileReader and BufferedReader

Example :


```
[SIZE=2][B]
String line;
try {
    FileReader fr = new FileReader("Hello.java");
    BufferedReader br = new BufferedReader(fr);
    line = br.readLine();
    while (line != null) {
        System.out.println(line);
        line = br.readLine();
    }
    br.close();
    fr.close();
} catch (IOException ioe) {
    System.out.println(ioe.getMessage());
} 
[/B][/SIZE]
```


----------



## Chicon (Jul 29, 2004)

Caliraj said:


> Hi,
> Thanks for the reply.But Im unable to understand why it gives the 1st line only as output if i replace -1 with 11. COuld you explain the logic?
> Thanks,
> Cali


In your coding, you're reading character by character. Therefore, in each loop of your *while* statement, the return value of the *read* method will be 1.

You may use an array of bytes instead of a character to read your file.

Exemple :


```
[SIZE=2][B]
int bufferSize = 32;    
byte[] buffer = new byte[bufferSize];  // the array of bytes in which
                                       // the content of the buffered input stream
                                       // will be stored
int count;                             // counter of bytes being read
String result;                         // will be used to show the content of the
                                       // array of bytes
try {
    FileInputStream fis = new FileInputStream("Hello.java");
    BufferedInputStream bis = new BufferedInputStream(fis);
    count = bis.read(buffer, 0, bufferSize);      // the second parameter 0 indicates the offset from
                                                  // which the data will be stored in the array
    while (count != -1) {
        result = new String(buffer, 0, count);
        System.out.println("Counter = " + count + " array content <" + result + ">");
        count = bis.read(buffer, 0, bufferSize);
    }
    bis.close();
    fis.close();
} catch (IOException ioe) {
    System.out.println(ioe.getMessage());
}
[/B][/SIZE]
```


----------



## Caliraj (Mar 22, 2006)

Hi, 
thanks for the answers.I would like to know the difference b/w read() and readChar() methods.Could you let me know the context in which these methods can be used?
Thanks once again.
Cali


----------



## Chicon (Jul 29, 2004)

*readChar()* is a method of the interface *DataInput* and is not used by *FileInputStream* and *BufferedInputStream*.
That method is only suitable for reading bytes written by the *writeChar()* method of interface *DataOutput*

Also, it is not a good idea to use characters while reading a file for the following reason :



Sun Java Tutorial said:


> A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
> 
> Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. (For more information, see X/Open Company Ltd., "File System Safe UCS Transformation Format (FSS_UTF)", X/Open Preliminary Specification, Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.)
> 
> ...


Link : http://java.sun.com/j2se/1.3/docs/api/java/io/DataInputStream.html


----------



## Caliraj (Mar 22, 2006)

Hi chicon,
Sorry for this chain of mails.....actually I wanted to know teh difference b/w erad() and readLine() as wella s teh contexts in which they are used......Could you explain the significance of tehse methods?
Thanks once again,
Cali


----------



## IMM (Feb 1, 2002)

just a fix for a typo above -- when I said 
_ b becomes the character read_
it should have been
_ ch becomes the character read_


----------



## Chicon (Jul 29, 2004)

The method *read()* in a *BufferedInputStream* returns an integer.


Sun Java Tutorial said:


> Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.


The method is inherited from the *FilerInputStream* which is itself an extension of the *InputStream* class.

The method *readLine()* in a *BufferedReader* returns a string.


Sun Java Tutorial said:


> Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
> Returns a String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached


The method is not inherited. *BufferedReader* is an extension of the *Reader* class.

*InputStream* classes are designed to read *bytes*.
*Reader* classes are designed to read *characters*.

*OutputStream* classes are designed to write *bytes*.
*Writer* classes are designed to write *characters*.


----------

