0

I was reading a tutorial for using I/O streams in java and stumbled upon the following code for inputstream:

    InputStream input = new FileInputStream("c:\\data\\input-file.txt");
    int data = input.read(); 
    while(data != -1){
    data = input.read();
     }

The tutorial mentions that InputStream returns only one byte at a time. So if I want to receive more bytes at a time, is that possible using a different method call?

3
  • 5
    Did you look in the documentation for InputStream? Commented May 30, 2014 at 20:46
  • Thanks for the link. It clearly mentions how to read 'n' bytes. Commented May 30, 2014 at 20:47
  • I forgot to answer your question: 'yes' Commented May 30, 2014 at 20:49

3 Answers 3

1

Use the read(byte[]) overload of the read() method. Try the following:

byte[] buffer = new byte[1024];
int bytes_read = 0;
while((bytes_read=input.read(buffer))!= -1)
{
// Do something with the read bytes here
}

Further you can channel your InputStream into a DataInputStream to do more specific tasks like reading integers, doubles, Strings etc.

DataInputStream dis=new DataInputStream(input);
dis.readInt();
dis.readUTF();
Sign up to request clarification or add additional context in comments.

Comments

1

Use the read method with an array of bytes. It returns the number of bytes read from the array which isnt always the same length as your array so its important you store that number.

InputStream input = new FileInputStream("c:\\data\\input-file.txt");
int numRead; 
byte [] bytes = new byte[512];
while((numRead = input.read(bytes)) != -1){
     String bytesAsString = new String(bytes, 0, numRead);
}

Comments

1

Take a look in the official doc here http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html You can use read(int n) or read(byte[], int, int)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.