获取完整的InputStream

时间:2014-04-04 22:35:38

标签: java inputstream

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

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

2 个答案:

答案 0 :(得分:1)

你的while循环使用10将它限制为10.由于stream.read()在流的末尾返回-1,所以在while循环中使用它作为控件:

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

答案 1 :(得分:1)

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