开发者

Display program output in Notepad rather than on the console? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopen开发者_运维技巧ed, visit the help center. Closed 10 years ago.

How do I display the output text in Notepad rather than displaying it on the console in Java?


redirect it like this in your terminal.

java ClassName > your-file

or 

java ClassName 1> your-file

here
1 stands for standard output.
2 stands for standard error.
0 stands for standard input.

use >> for append mode, '<' for input mode.

if you need to redirect both error and output stream to a same file, try

  java ClassName 2>&1 your-file

Or use the below java API calls in your code.

System.setErr(PrintStream err);

System.setIn(InputStream in);

System.setOut(PrintStream out); 


Try this

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

    }

}

}

Hope it helps.


Use logging instead of system.out. check log4j or other logging apis. It will also help you in using the printing info,only debug, only errors etc.

Also if you want to set system out to a file you can do that through a command >> File

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜