我正在尝试读取 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 堆空间错误。
请让我知道代码有什么问题?
提前致谢!