0

我真的不明白问题出在哪里。我想将字符打印到文本文件中,并且我想使用 printWriter 来做同样的事情。如果文件有“;”,我想用新行替换它,这就是我正在做的事情,

public static void downloadFile_txt(String sourceFilePathName, String contentType, String destFileName, HttpServletResponse response) throws IOException, ServletException
 {
     File file = new File(sourceFilePathName);
     //FileInputStream fileIn = new FileInputStream(file);
     FileReader fileIn = new FileReader(file); 
     long fileLen = file.length();
     response.setContentType(contentType);
     response.setContentLength((int)fileLen);

     response.setHeader("Content-Disposition", String.valueOf((new  StringBuffer("attachment;")).append("filename=").append(destFileName)));

     PrintWriter pw =  response.getWriter();


     // Loop to read and write bytes.
     int c=-1;      
     while ((c = fileIn.read()) != -1)
     {

         if(c!=59)
         {
              pw.print((char)c);
         }
         else
         {
              pw.println();
         }
     }
     pw.flush();
     pw=null;        
     fileIn.close();        
}

但是我的文件正在打印除最后一个字符之外的所有内容。例如输入=

:00004000,FFAD,2 Byte Ch;
:0000FFBD,FFBE,2 Byte Ch;
:0000FFBF,FFFF,2 Byte Ch;

我得到的输出

:00004000,FFAD,2 Byte Ch
:0000FFBD,FFBE,2 Byte Ch
:0000FFBF,FFFF,2 Byte C

最后一个“h”没有被打印出来。

提前致谢

4

3 回答 3

3

Apw.flush();可能会帮助你。

public class FlushPrintWriter {

    public static void main(String[] args) throws IOException  {
        FileReader fileIn = new FileReader("in.txt");
        FileWriter out = new FileWriter("out.txt");
        PrintWriter pw = new PrintWriter(out);
        int c;        
        while ((c = fileIn.read()) != -1) {
            if(c!=59) {
               pw.print((char)c);
            } else {
               pw.println();
            }
        }
        pw.flush();
    }
}

输出

:00004000,FFAD,2 字节通道

:0000FFBD,FFBE,2 字节通道

:0000FFBF,FFFF,2 字节通道

正如预期的那样。

(不要这样处理你IOException的 s - 并关闭你的读者和作者 - 这只是为了演示!)


编辑:现在您的代码甚至无法编译(两个变量称为fileIn?)!

即使运行您现在提到的 servlet 代码,我也无法重现您的问题,并且输出与您预期的一样。所以这是我放弃了。我开始怀疑最终;文件不在您的源文件中,或者您的应用程序正在执行更多处理而您没有向我们展示。

于 2012-08-21T12:28:34.767 回答
1

试试flush() 或close() 你的打印作者。

可能最好逐行阅读,使用 String.replace() 替换字符

于 2012-08-21T12:30:14.690 回答
0

运行while循环直到文件大小

 int fileSize=file.length();
 while(fileSize>0)
 {
    //do your task of reading charcter and printing it or whatever you want
    fileSize--;
 }
于 2012-08-21T12:34:30.370 回答