我正在使用像这样的java代码写一个文件。
File errorfile = new File("ErrorFile.txt");
FileWriter ef = new FileWriter(errorfile, true);
BufferedWriter eb = new BufferedWriter(ef);
eb.write("the line contains error");
eb.newLine();
eb.write("the error being displayed");
eb.newLine();
eb.write("file ends");
eb.close();
ef.close();
此文件正在保存在服务器上。现在,当我使用java代码下载文件时,它会跳过换行符。下载代码是:
String fname = "ErrorFile.txt";
BufferedInputStream filein = null;
BufferedOutputStream output = null;
try {
File file = new File(fname); // path of file
if (file.exists()) {
byte b[] = new byte[2048];
int len = 0;
filein = new BufferedInputStream(new FileInputStream(file));
output = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/force-download");
response.setHeader("content-Disposition", "attachment; filename=" + fname); // downloaded file name
response.setHeader("content-Transfer-Encoding", "binary");
while ((len = filein.read(b)) > 0) {
output.write(b, 0, len);
output.flush();
}
output.close();
filein.close();
}
} catch (Exception e1) {
System.out.println("e2: " + e1.toString());
}
现在当我打开下载的文件时,它应该如下所示:
the line contains error
the error being displayed
file ends
但输出是
the line contains error (then a box like structure) the error being displayed (then a box like structure) file ends.
请建议......
答案 0 :(得分:2)
@BalusC这是正确的...我的服务器是linux,客户端是Windows ..这是什么解决方案?
任何初级开发人员或至少计算机爱好者应该知道基于Linux / Unix的操作系统使用\n
作为换行符,并且Windows使用\r\n
作为换行符。 \n
在Windows中失败,但是\r\n
在Linux / Unix中运行正常(必须这样,否则例如也强制\r\n
的HTTP也会在Linux / Unix中失败)。
The newLine()
method仅在您的服务器上打印系统的默认换行符\n
。但是,您的客户端(基于Windows)需要\r\n
。
您需要替换
eb.newLine();
通过
eb.write("\r\n");
为了让它跨平台工作。
答案 1 :(得分:0)
我将此代码用于我的问题......以及它的工作......
String fname = "ErrorFile.txt";
BufferedInputStream filein = null;
BufferedOutputStream output = null;
try {
File file = new File(fname); // path of file
if (file.exists()) {
int len = 0;
filein = new BufferedInputStream(new FileInputStream(file));
output = new BufferedOutputStream(response.getOutputStream());
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("content-Disposition", "attachment; filename=" + fname); // downloaded file name
while ((len = filein.read()) != -1) {
output.write(len);
output.flush();
}
output.close();
filein.close();
}
} catch (Exception e1) {
System.out.println("e2: " + e1.toString());
}