2013-06-28 27 views
1

我正在使用这样的java代码写入文件。使用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

如果服务器运行的是Linux/Unix和客户端运行Windows,可以发生。 – BalusC

+0

它是如何在另一端下载的?你不告诉 – fge

+0

@BalusC thats correct ...我的服务器是Linux和客户端是Windows ..是theris任何解决方案? – anonymous

回答

2

@BalusC thats correct ... m Ÿ服务器是Linux和客户端是Windows ..是theris任何解决方案?

任何开发商开始或至少电脑爱好者应该知道的Linux/Unix操作系统下使用\n作为换行符和Windows使用\r\n作为换行符。 \n在Windows中失败,但\r\n在Linux/Unix中正常工作(它必须,否则,例如HTTP也会在Linux/Unix中失败)。

The newLine() method用于打印换行符的打印机仅打印系统的默认换行符,因此\n在您的服务器上。但是,您的客户端基于Windows,预计\r\n

您需要通过

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

为了得到它的跨平台工作,以取代

eb.newLine(); 

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