2013-08-22 19 views
0

我試圖讀取XML文件並使用HttpPost發送到本地服務器。在服務器端讀取數據並寫入文件時,總是會丟失幾行。使用Servlet將數據寫入文件的問題

客戶端代碼:

HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx:yyyy/FirstServlet/HelloWorldServlet");  
    InputStreamEntity reqEntity = new InputStreamEntity(
    new FileInputStream(dataFile), -1); 
    reqEntity.setContentType("binary/octet-stream"); 

    // Send in multiple parts if needed 
    reqEntity.setChunked(true); 
    httppost.setEntity(reqEntity); 
    HttpResponse response = httpclient.execute(httppost); 
    int respcode = response.getStatusLine().getStatusCode(); 

Server代碼:

response.setContentType("binary/octet-stream"); 
    InputStream is = request.getInputStream(); 
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\Files\\copyFile.xml"))); 
    byte[] buf = new byte[4096]; 
    for (int nChunk = is.read(buf); nChunk!=-1; nChunk = is.read(buf)) 
    { 
     bos.write(buf, 0, nChunk); 
    } 

我嘗試使用BufferedReader類爲好,但同樣的問題。

BufferedReader in = new BufferedReader( 
      new InputStreamReader(request.getInputStream())); 
    response.setContentType("binary/octet-stream"); 
    String line = null; 
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\Files\\copyFile.xml"))); 
     while((line = in.readLine()) != null) { 
      line = in.readLine(); 
      bos.write((line + "\n").getBytes()); 
    } 

我試過使用掃描儀以及。在這種情況下,只有當我使用StringBuilder並再次將值傳遞給BufferedOutputStream時,它才能正常工作。

response.setContentType("binary/octet-stream"); 
    StringBuilder stringBuilder = new StringBuilder(2000); 
    Scanner scanner = new Scanner(request.getInputStream()); 
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\Files\\copyFile.xml"))); 
    while (scanner.hasNextLine()) { 
     stringBuilder.append(scanner.nextLine() + "\n"); 
    } 
    String tempStr = stringBuilder.toString(); 
    bos.write(tempStr.getBytes()); 

我不能使用上述邏輯處理非常大的XML,因爲轉換爲字符串值會拋出Java堆空間錯誤。

請讓我知道代碼的問題是什麼?

在此先感謝!

回答

1

flush()close()您的輸出流。會發生什麼情況是你沒有刷新,最後幾行保留在內部緩衝區中並且沒有寫出來。

所以在您的服務器代碼:

response.setContentType("binary/octet-stream"); 
InputStream is = request.getInputStream(); 
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\Files\\copyFile.xml"))); 
byte[] buf = new byte[4096]; 
for (int nChunk = is.read(buf); nChunk!=-1; nChunk = is.read(buf)) { 
    bos.write(buf, 0, nChunk); 
} 
bos.flush(); 
bos.close(); 
+0

它的工作完美!謝謝你的幫助。 –