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?
Most HackerRank challenges require you to read input from stdin (standard input) and write output to stdout (standard output). Alternatively, you can use the BufferedReader class. In this challenge, you must read integers from stdin and then print them to stdout. Each integer must be printed on a new line.
The standard input(stdin) can be represented by System.in in Java. The System.in is an instance of the InputStream class. It means that all its methods work on bytes, not Strings. To read any data from a keyboard, we can use either a Reader class or Scanner class.
stdin / stdout are logical names for open files that are forwarded (or initialized) by the process that has started a given process. Actually, with the standard fork-and-exec pattern the setup of those may occur already in the new process (after fork) before exec is being called.
You achieve standard output by calling Java's System. out. print() and System. out.
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")));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With