gpt4 book ai didi

java - 使用 Servlet 将数据写入文件时出现问题

转载 作者:行者123 更新时间:2023-12-01 14:12:47 24 4
gpt4 key购买 nike

我正在尝试读取 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 堆空间错误。

请告诉我代码有什么问题?

提前致谢!

最佳答案

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

关于java - 使用 Servlet 将数据写入文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18372365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com