Redirecting stdout and stdin - Java

When writing code, it’s c/c++pretty convenient to use freopen () . 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;
}

Using freopen()this way is very useful when we are trying to debug / test a small console application. We can put the input sample into the file 'input.txt' once and reuse it every time instead of manually entering the input in the terminal / console. And in the same way, we can print the output in the file 'output.txt .

java, . - / , . / . - ?

+4
3

System.out

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

System.err

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

System.in

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

* to reset

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

, System.setIn System.setOut.

System.setIn(new FileInputStream(new File("input.txt")));
System.setOut(new PrintStream(new File("output.txt")));
+4

, , , , .

import java.io. *; , :

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

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

To write to the data file, not standard, you can do this to change the standard output to the 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 be written to the file.

+1
source

Source: https://habr.com/ru/post/1569749/


All Articles