2014-04-04 19 views
-1

我在Web服務器上的工作,我被困在HTTP PUT方法......我目前只能押10個字節當他試圖將文件上傳客戶端的數據,波紋管是我迄今爲止。入門完整的InputStream

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

請告訴我如何獲得客戶端寫入的儘可能多的輸入。

+0

http://docs.oracle.com/javase/tutorial/essential/io/streams.html –

+0

可能重複[如何讀取HTTP輸入流](http://stackoverflow.com/問題/ 9856195 /如何閱讀-AN-HTTP-輸入流) –

+0

溴伊恩羅奇它不回答我的問題! –

回答

1

通過使用10.自stream.read()返回-1在流的末尾while循環它限制在10,使用while循環的控制:基於

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

如果你在你的答案中刪除了count變量,我認爲它會更完整。 –

+0

我想他可能希望它在知道到底該文件有多少字節了。 – developerwjk

+0

好,好,我只是認爲他用這種只檢查前10個字節輸入號碼。 –

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