我写了这段代码来将二进制数据转换成ascii,现在我想把控制台结果写到一个文本文件output.txt中。它可以运行,但问题是它将第一行打印到控制台,并从第二行开始将输出写入到文本文件,换句话说,它跳过了第一行!
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盘
发布于 2012-04-24 15:54:49
代码
System.err.println("Error: " + e.getMessage());将写入错误流,而不是输出流。
System.setOut(out);在这里您正在设置out流,err流仍然默认到控制台。
发布于 2012-04-24 15:57:07
您不使用您的out流。
发布于 2012-04-24 15:57:56
这一行
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或(低效地)将字符连接成字符串。
此外,当您完成编写时,您应该关闭()您创建的流。在你开始编写更大的程序之前,这只是一个很好的实践,在你开始编写更大的程序之前,让流打开可能会导致错误。
https://stackoverflow.com/questions/10293884
复制相似问题