![](/img/trans.png)
[英]Java InputStream NullPointerException with InputStream
[英]Java InputStream
我正在阅读有关在Java中使用I / O流的教程,偶然发现了inputstream的以下代码:
InputStream input = new FileInputStream("c:\\data\\input-file.txt");
int data = input.read();
while(data != -1){
data = input.read();
}
本教程提到InputStream一次仅返回一个字节。 因此,如果我想一次接收更多字节,是否可以使用其他方法调用?
将read方法与字节数组一起使用。 它返回从数组读取的字节数,该字节数并不总是与数组相同,因此存储该数字很重要。
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);
}
使用read()
方法的read(byte[])
重载。 请尝试以下操作:
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();
在此处查看官方文档http://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html您可以使用read(int n)或read(byte [],int, int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.