如何重定向程序的输入流,使其从控制台作为主要>运行。 myProgram没有在代码中指定文件名?这就是我到目前为止所拥有的。
public static void main (String[ ] args) throws IOException {
BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
while(in.next != null){
in.read();
}
}
我知道这将与System.setIn有关,但我不知道如何编写它以便在Main>之后检测文件名。输入。
答案 0 :(得分:0)
使用标准System.in
和System.out
流。
答案 1 :(得分:0)
为了重定向流,它是System类的方法:setIn(),setOut(),setErr(),这将有所帮助。 现在,为了重定向流,您必须将其重定向到特定的文件类型。
例如,如果要重定向输出流,则需要使用setOut()。 setOut()接受一个print流对象,print stream有一个参数化构造函数,它接受字符串,你将以这种方式提供路径。
这里是链接到测试文件的程序。 无论何时在其上调用println()方法,在这种情况下,流都会将其重定向到测试文件而不是输出控制台。
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");
}
}
这是输入流的程序:
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);
}
}