5

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?

Community
  • 1
  • 1
Razib
  • 10,965
  • 11
  • 53
  • 80

3 Answers3

4

You can reassign the streams using System.setIn and System.setOut.

System.setIn(new FileInputStream(new File("input.txt")));
System.setOut(new PrintStream(new File("output.txt")));
M A
  • 71,713
  • 13
  • 134
  • 174
3

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));
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24
1

For getting data from a file rather than user input, you just have to change what you do when you construct your Scanner a little bit.

import java.io.*; for some classes, then do this:

try{
    Scanner input = new Scanner(new File("input_file_name.in"));
}
catch(FileNotFoundException e){
    e.printStackTrace();
}

Then just use the scanner as normal and it will read from the file.

To write to a data file rather than standard out, you can do this to change the standard output to a data file:

try{
FileOutputStream f = new FileOutputStream(new File("output_file_name.out"));
    PrintStream p = new PrintStream(f);
    System.setOut(p);
}
catch(Exception e){
    e.printStackTrace();
}

All operations with System.out.print() and System.out.println() will write to the the file.

kirbyquerby
  • 735
  • 5
  • 16