In order to redirect the streams, it is the methods of the System class: setIn(), setOut(), setErr() , which will help.
now in order to redirect the stream you have to redirect it to the specific file type.
For instance if want to redirect the output stream, then you need to use the setOut(). the setOut() takes an object of print stream and print stream has a parameterized constructor which takes string, you will be providing the path in that manner.
here's the program which is linked to a test file.
whenever you call the println() method on it, the stream will redirect it to the test file instead of the output console in this case.
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class Redirect1 {
public static void main(String[] args)throws FileNotFoundException {
System.setOut(new PrintStream("C:\\Users\\nEW u\\Desktop\\Test.txt"));
System.out.println("Hello");
}
}
And here is the program for the input stream:
import java.io.*;
import java.lang.System;
public class Redirect {
public static void main(String[] args)throws IOException {
System.setIn(new FileInputStream("C:\\Users\\nEW u\\Desktop\\dev.txt"));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s="";
while((s=br.readLine())!=null)
System.out.println(s);
}
}
setIn(...)or anything of that sort. The System.in will refer to the file that was piped into your program without your doing anything.java MyClass < myFile.txtwill send myFile.txt to your MyClass program, assuming that you have a MyClass.class file there.