【问题标题】:Getting the full InputStream获取完整的 InputStream
【发布时间】:2014-04-04 22:35:38
【问题描述】:

我在 Web 服务器上工作,我被 HTTP 方法 PUT 卡住了……当他尝试上传文件时,我目前只能从客户端打赌 10 字节的数据,下面是我到目前为止所拥有的。

InputStream stream = connection.getInputStream();
OutputStream fos = Files.newOutputStream(path); 

int count = 0;

while (count < 10) {
  int b = stream.read();
  if (b == -1) break;

  fos.write(b);
  ++count;
}
fos.close();

请告诉我如何才能获得客户所写的尽可能多的输入。

【问题讨论】:

  • Brian Roach 它没有回答我的问题!
  • 解释如何从流中读取的教程当然可以。就像已经在 SO 上的许多 Q 一样。您编写的代码明确限制您的循环仅读取 10 个字节然后询问如何读取超过 10 个字节的事实......让我认为也许从一本关于 Java 的初学者书籍开始可能也是一个好主意。
  • 如果您认为这是一个愚蠢的问题,为什么不自己回答。不要那么自大。我清楚地说“我目前只能从客户端获取 10 个字节的数据”,因为这是我编写的代码。我想要的是获取所有数据,直到客户端停止写入或换行。

标签: java inputstream


【解决方案1】:

您通过使用 10 的 while 循环将其限制为 10。由于 stream.read() 在流结束时返回 -1,因此在 while 循环中使用它作为控件:

 int count = 0;
 int b = 0;
 while ((b=stream.read()) !=-1) 
 {
   fos.write(b);
   count++;
 }

【讨论】:

  • 我认为如果您删除答案中的计数变量会更完整。
  • 我想他可能希望它知道文件最后有多少字节。
  • 好的,很好,我只是以为他只是用这个来检查前 10 个字节的输入数字。
  • 但是客户端没有写更多它仍然会等待下一个流,我该怎么做,当客户端执行新行时,流将关闭要写入的先前字节文件?
【解决方案2】:
public void receiveFile(InputStream is){
        //Set a really big filesize
        int filesize = 6022386;
        int bytesRead;
        int current = 0;
        byte[] mybytearray = new byte[filesize];

        try(FileOutputStream fos = new FileOutputStream("fileReceived.txt");
            BufferedOutputStream bos = new BufferedOutputStream(fos)){

            //Read till you get a -1 returned by is.read(....)
            bytesRead = is.read(mybytearray, 0, mybytearray.length);
            current = bytesRead;

            do {
                bytesRead = is.read(mybytearray, current,
                        (mybytearray.length - current));
                if (bytesRead >= 0)
                    current += bytesRead;
            } while (bytesRead > -1);

            bos.write(mybytearray, 0, current);
            bos.flush();
            bos.close();
        }
        catch (FileNotFoundException fnfe){
            System.err.println("File not found.");
        } 
        catch (SecurityException se){
            System.err.println("A Security Issue Occurred.");
        } 
    }

基于此:FTP client server model for file transfer in Java

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2012-10-24
    • 2018-11-20
    • 2017-07-24
    • 1970-01-01
    相关资源
    最近更新 更多