如何在控制台中打印和在文本文件中打印
问题描述:
我的代码需要程序在文本文件中打印一组数字。如何在控制台中打印和在文本文件中打印
因此,在此期间,我想改变我的输出流:
System.setOut(new PrintStream(new FileOutputStream("data.txt")));
那么,如何将返回打印控制台?
任何帮助,将不胜感激。 谢谢。
答
这个例子可以帮助您:
static void redirectIfNecessary() {
/* If we have been exec'd by Rio (such as a service that has been declared to be forked,
* stdout and stderr have already been redirected */
if(System.getenv("RIO_EXEC")==null && System.console()==null) {
redirectToLogger();
}
}
static void redirectToLogger(){
System.setOut(new PrintStream(System.out){
public void print(String s){
stdOutLogger.info(s);
}
});
System.setErr(new PrintStream(System.err){
public void print(String s){
stdErrLogger.error(s);
}
});
}
答
下面的例子可能会有所帮助....
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
// EditorConsole.systemOut.println("editor window activated");
base.handleActivated(Editor.this);
// mode.handleActivated(Editor.this);
fileMenu.insert(base.getSketchbookMenu(), 2);
fileMenu.insert(base.getRecentMenu(), 3);
// fileMenu.insert(mode.getExamplesMenu(), 3);
sketchMenu.insert(mode.getImportMenu(), 4);
mode.insertToolbarRecentMenu();
}
// added for 1.0.5
// http://dev.processing.org/bugs/show_bug.cgi?id=1260
public void windowDeactivated(WindowEvent e) {
// EditorConsole.systemErr.println("editor window deactivated");
// mode.handleDeactivated(Editor.this);
fileMenu.remove(base.getSketchbookMenu());
fileMenu.remove(base.getRecentMenu());
// fileMenu.remove(mode.getExamplesMenu());
sketchMenu.remove(mode.getImportMenu());
mode.removeToolbarRecentMenu();
}
});
为什么要用' System.out.print'而不是将'PrintStream'传递给执行打印和打印的代码而不是传递给'PrintStream'?如果这是不可能的:将'System.out'存储到变量,更改'System.out',打印某些内容,将'System.out'设置为旧值。 – fabian