简体   繁体   中英

Java InputStream

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?

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);
}

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();

在此处查看官方文档http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html您可以使用read(int n)或read(byte [],int, int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM