2014-04-03 65 views
0

我目前正在編寫一個Web服務器編程,我正在使用HTTP PUT方法。當客戶端連接是他的類型是這樣的:使用Java寫入文件

PUT /newfile.txt HTTP/1.1 
Host: myhost 
BODY This text is what has to be written to the new created file 

我希望能夠給客戶端請求的主體寫入到創建的文件。

這是我到目前爲止,它的工作,但我按下輸入後,它停留在那裏。

InputStream is = conn.getInputStream(); 
OutputStream fos = Files.newOutputStream(file); 

int count = 0; 
int n = 10; 

while (count < n) { 
     int b = is.read(); 
     if (b == -1) break; 
     fos.write(b); 
     ++count; 
} 

fos.close(); 
conn.close(); 
+2

它停留在哪裏?在連接輸入流關閉之前不會返回-1 –

回答

1

你可以試試這個

Scanner sc = new Scanner(is); 

Scanner將使您能夠輕鬆地閱讀文件到String。您可以使用regex分開BODY。你只需要提供它作爲next方法Scanner的參數。


分離之後,您需要將String寫入該文件。只需使用

FileWriter writer = new FileWriter(file); 
writer.write(bodyContentString); 
writer.flush(); 
writer.close(); 

祝你好運。