1

我正在使用这样的 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.

请建议...

4

2 回答 2

2

@BalusC 那是正确的......我的服务器是linux,客户端是windows ..有什么解决方案吗?

任何初级开发人员或至少计算机爱好者都应该知道基于 Linux/Unix 的操作系统\n用作换行符,而 Windows\r\n用作换行符。\n在 Windows 中失败,但在\r\nLinux/Unix 中工作正常(它必须,否则例如 HTTP 也强制\r\n在 Linux/Unix 中也会失败)。

newLine()您用于打印换行符方法\n仅打印系统的默认换行符,因此在您的服务器上。但是,您的基于 Windows 的客户端需要\r\n.

你需要更换

eb.newLine();

经过

eb.write("\r\n");

为了让它跨平台工作。

于 2013-06-28T12:07:11.753 回答
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());
    }
于 2013-07-01T04:05:15.850 回答