0

我编写了这段代码来将二进制数据转换为 ascii ,现在我想将控制台结果写入文本文件 output.txt 。它运行但问题是它将第一行打印到控制台并开始从第二行将输出写入文本文件,换句话说,它跳过了 fisr 行!

public static void main(String args[])
  {
  try{
  // Open the file that is the first 
  // command line parameter
  FileInputStream fstream = new FileInputStream("textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {

      String input = br.readLine();
            String output = "";
            for(int i = 0; i <= input.length() - 8; i+=8)
            {
                int k = Integer.parseInt(input.substring(i, i+8), 2);
                output += (char) k;
            }

                System.out.println("string: " + output);
          orgStream = System.out;
          fileStream = new PrintStream(new FileOutputStream("d:/output.txt",true));

          // Redirecting console output to file
          System.setOut(fileStream);


              } 
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

这些行负责将结果写入 output.txt:

 System.out.println("string: " + output);
          orgStream = System.out;
          fileStream = new PrintStream(new FileOutputStream("d:/output.txt",true));

          // Redirecting console output to file
          System.setOut(fileStream);

如何在 eclipse 中保存输出以便能够再次使用它?现在我保存在D盘

4

4 回答 4

1

你不使用你的out流。

于 2012-04-24T07:57:07.403 回答
1

这条线

PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);

只需将您写入 System.out 的任何内容重定向到 FileOutputStream。由于您没有向 System.out 写入任何内容,因此不会向 output.txt 写入任何内容。

您可以简单地将输出写入您创建的 PrintStream,而不是重定向 System.out。因此,首先在 while 循环外创建 PrintStream,然后在循环内将您创建的每个字符直接写入 PrintStream。无需重定向 System.out 或(低效)将字符连接成字符串。

此外,当您完成编写时,您应该关闭()您创建的流。这只是在开始编写更大的程序之前学习的一个好习惯,因为让流打开可能会导致错误。

于 2012-04-24T07:57:56.393 回答
0

代码
System.err.println("Error: " + e.getMessage());将写入错误流而不是输出流..

          System.setOut(out);

在这里您正在设置输出流,错误流仍然默认为控制台。

于 2012-04-24T07:54:49.390 回答
0

我想你需要一个

out.flush ();

到底。再看一遍,我明白了,你从来没有写过任何东西。您只想按照 Anantha 的建议编写错误消息吗?

你忘记了:

System.out.println (output);
于 2012-04-24T07:55:00.933 回答