在记事本中而不是在控制台上显示程序输出?

时间:2011-03-24 04:20:23

标签: java

如何在记事本中显示输出文本而不是在Java中将其显示在控制台上?

3 个答案:

答案 0 :(得分:2)

在您的终端中将其重定向。

java ClassName > your-file

or 

java ClassName 1> your-file

这里        1代表标准输出        2代表标准误差        0代表标准输入。

使用>>作为追加模式,'<'用于输入模式。

如果您需要将错误和输出流重定向到同一个文件, 尝试

  java ClassName 2>&1 your-file

或者在代码中使用below java API调用。

System.setErr(PrintStream err);

System.setIn(InputStream in);

System.setOut(PrintStream out); 

答案 1 :(得分:1)

试试这个

public class RedirectIO
{



public static void main(String[] args)
{
    PrintStream orgStream   = null;
    PrintStream fileStream  = null;
    try
    {
        // Saving the orginal stream
        orgStream = System.out;
        fileStream = new PrintStream(new FileOutputStream("out.txt",true));
        // Redirecting console output to file
        System.setOut(fileStream);
        // Redirecting runtime exceptions to file
        System.setErr(fileStream);
        throw new Exception("Test Exception");

    }
    catch (FileNotFoundException fnfEx)
    {
        System.out.println("Error in IO Redirection");
        fnfEx.printStackTrace();
    }
    catch (Exception ex)
    {
        //Gets printed in the file
        System.out.println("Redirecting output & exceptions to file");
        ex.printStackTrace();
    }
    finally
    {
        //Restoring back to console
        System.setOut(orgStream);
        //Gets printed in the console
        System.out.println("Redirecting file output back to console");

    }

}

}

希望它有所帮助。

答案 2 :(得分:0)

使用日志记录而不是system.out。检查log4j或其他日志记录apis。它还可以帮助您使用打印信息,仅调试,只有错误等。

此外,如果您想将系统设置为文件,您可以通过命令>>执行此操作。文件