使用Servlet将数据写入文件的问题

时间:2013-08-22 05:35:04

标签: java servlets io

我正在尝试读取XML文件并使用HttpPost发送到本地服务器。在服务器端读取数据并写入文件时,总是丢失几行。

客户代码:

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

服务器代码:

    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 个答案:

答案 0 :(得分: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();