javac++debuggingiofreopen

Redirecting the stdout and stdin - Java


While writing c/c++ code it's pretty handy to use freopen(). Please see the following code snippet -

int main(){

 int n1, n2, result;

 freopen("input.txt", "rb", stdin);
 freopen("output.txt", "wb", sdtout);

 while(scanf("%d %d", &n1, &n2)==2 && n1>0 &&n2>0){
  ...
  ...
  ...
  printf("%d\n", result);
 }

 return 0;
}

The use of freopen() in this way is very useful when we are trying to debug/test a small console application. We can put the sample input in 'input.txt' file once and reuse them every time instead of giving the input manually in terminal/console. And similarly we can print the output in 'output.txt' file.

Now I am looking foreword a similar type of solution in java so that I can redirect input and output to text file. My target is to simplify the small console/program debugging while manipulating with some data. Providing these data to terminal/console recurrently as input is somewhat cumbersome. Can anyone suggest some good tips for doing this?


Solution

  • For System.out

    System.setOut(new PrintStream(new File("output-file.txt")));
    

    For System.err

    System.setErr(new PrintStream(new File("err_output-file.txt")));
    

    For System.in

    System.setIn(new FileInputStream(new File("input-file.txt")));
    

    *to reset back to console

    System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
    System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.out)));
    System.setIn(new FileInputStream(FileDescriptor.in));