Reputation: 63
How do I redirect the input stream for a program so that it will run from the console as main > myProgram with no filename specified within the code? This is what I have so far.
public static void main (String[ ] args) throws IOException {
BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
while(in.next != null){
in.read();
}
}
I know it's going to be something to do with System.setIn but I have no clue as to how to write it so that it will detect a filename after Main > is typed.
Upvotes: 1
Views: 2573
Reputation: 1
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);
}
}
Upvotes: 0