这是今天看到一个分类,值得看一下,我就先收藏在这了:
下面我们来讲重定向标准输入输出:
前面介绍过,标准输入输(System.in,System.out)出就是键盘输入和显示屏输出(也是eclipse控制台输出),在System类还提供了三个重定向标准输入输出的方法:
static void setErr(PrintStream err) //重定向标准错误输出流
static void setIn(InputStream in) //重定向标准输入流
static void setOut(PrintStream err) //重定向标准输出流
例1:重定向标准输出流
public static void main(String[] args) throws IOException{
PrintStream ps=new PrintStream(new FileOutputStream("out.txt"));
PrintStream out = System.out;//如果想重定向回标准输出,必须提前保存标准输出,如果这句话放在setOut后面会无效
System.setOut(ps);//将标准输出流重定向到ps输出流
System.out.println("输入到文件");
System.setOut(out);
System.out.println("输入到控制台");
}
例2:重定向标准输入
public static void main(String[] args) throws IOException{
//将标准输入重定向到fis输入流
FileInputStream fis=new FileInputStream("in.txt");
System.setIn(fis);
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
System.out.println("你输入内容:"+str);
}