【问题标题】:How to alternate between printing in console and printing in a text file如何在控制台打印和文本文件打印之间切换
【发布时间】:2016-06-15 20:58:37
【问题描述】:

我的代码要求程序在文本文件中打印一个数字数组。

所以,在这些期间,我想改变我的输出流:

System.setOut(new PrintStream(new FileOutputStream("data.txt")));

那么,我将如何返回控制台中的打印?

任何帮助将不胜感激。 谢谢。

【问题讨论】:

  • 为什么要使用System.out.print 而不是将PrintStream 传递给执行打印的代码并将打印传递给PrintStream?如果这不可能:将System.out 存储到变量中,更改System.out,打印一些内容,将System.out 设置为旧值。

标签: java system outputstream


【解决方案1】:

这个例子可以帮助你:

https://github.com/dreedyman/Rio/blob/master/rio-start/src/main/java/org/rioproject/start/LogManagementHelper.java#L45

    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);
        }
    });
}

【讨论】:

    【解决方案2】:

    以下示例可能会有所帮助....

        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();
            }
          });
    

    完整代码:http://code.openhub.net/file?fid=LfGSIGX0O67nvFyO4lEKQDA5zxE&cid=80HR_JtEBgg&s=How%20to%20alternate%20between%20printing%20in%20console%20and%20printing%20in%20a%20text%20file&pp=0&fl=Java&ff=1&filterChecked=true&fp=1237&mp,=1&ml=0&me=1&md=1&projSelected=true#L0

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多