我正在阅读关于在java中使用I/O流的教程,无意中发现了以下输入流代码:
InputStream input = new FileInputStream("c:\\data\\input-file.txt");
int data = input.read();
while(data != -1){
data = input.read();
}本教程提到,InputStream一次只返回一个字节。因此,如果我想一次接收更多字节,是否可以使用不同的方法调用?
发布于 2014-05-30 21:05:18
使用read(byte[])重载的read()方法。尝试以下几点:
byte[] buffer = new byte[1024];
int bytes_read = 0;
while((bytes_read=input.read(buffer))!= -1)
{
// Do something with the read bytes here
}此外,您还可以将您的InputStream引导到DataInputStream中,以执行更具体的任务,如读取整数、双数、字符串等。
DataInputStream dis=new DataInputStream(input);
dis.readInt();
dis.readUTF();发布于 2014-05-30 21:01:12
使用带有字节数组的朗读方法。它返回从数组中读取的字节数,而数组的长度并不总是与数组的长度相同,所以重要的是要存储这个数字。
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);
}发布于 2014-05-30 21:09:47
看看这里的官方文档http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html,您可以使用read(int n)或read(byte[],int,int)。
https://stackoverflow.com/questions/23963159
复制相似问题