今天看到一篇文章:总结了下,怎么样将System.out.println("程序执行完毕!");这句话的内容输入到文件中。
一般我们在程序中写入这句话,执行的时候会在控制台打印出这句话。但是怎么样让他不显示在控制台,输入到指定的文件中呢?
FileOutputStream fos = null;
PrintStream ps = null;
PrintStream temPS = null;
try {
fos = new FileOutputStream(filePath, true);
ps = new PrintStream(fos);
if (ps != null) {
temPS = System.out;
System.setOut(ps);
}
int ln = 0;
for (char c = 0; c <= 60000; c++) {
System.out.print(c + " ");
ln++;
if (ln >= 10) {
System.out.println();
ln = 0;
}
}
fos.close();
ps.flush();
ps.close();
System.setOut(temPS);
System.out.println("程序执行完毕!");
} catch (FileNotFoundException e) {
System.out.println("文件不存在!");
} catch (IOException e) {
System.out.println("文件读取错误!");
}
}
看以上的代码:
temPS = System.out;
System.setOut(ps); 因为ps是一个printWriter对象,所以这里会将System.out.print();打印的内容输入到printWriter对象中,也就是输入到printWriter对象所指定的文件中。
System.setOut(temPS);这里又使用了temPS 对象,也就是说又把内容的显示交给了控制台:在他的后面出现的System.out.print();打印出胡的语句都会显示在控制台。
至此完毕,如要更深入的了解java io的处理方式,可以参考 张燕广 的博客点击打开链接