【问题标题】:Java InputStreamJava 输入流
【发布时间】:2014-05-30 20:44:13
【问题描述】:

我正在阅读在 java 中使用 I/O 流的教程,偶然发现了以下输入流代码:

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

教程中提到 InputStream 一次只返回一个字节。因此,如果我想一次接收更多字节,是否可以使用不同的方法调用?

【问题讨论】:

  • 感谢您的链接。它清楚地提到了如何读取“n”个字节。
  • 我忘了回答你的问题:'是的'

标签: java inputstream


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    对字节数组使用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);
    }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-09
        • 2012-07-19
        • 2012-11-17
        • 2018-05-25
        • 2012-07-29
        • 2011-06-16
        • 2011-04-25
        相关资源
        最近更新 更多