您的位置:首页 > 编程语言 > Java开发

java中重定向标准IO

2017-06-20 15:16 267 查看
1.  3个重定向方法

System类提供了3个重定向输入输出方法:

1)static void setErr(PrintStream err):重定向“标准“错误输出流。

2)static void setIn(InputStream in):重定向”标准“输入流。

3)static void setOut(PrintStream out):重定向”标准“输出流。

[java] view plain copy
import java.io.*;
import java.util.*;
class RedirectInOut
{
public static void main(String[] args)
{
try(PrintStream ps=new PrintStream(new FileOutputStream("out.txt"));//重定向标准输出为"out.txt"
FileInputStream fis=new FileInputStream("RedirectInOut.java")//重定向标准输入为"RedirectInOut.java"文件
)
{
System.setOut(ps);
System.out.println("这是一个重定向输出");
System.setIn(fis);
Scanner sc=new Scanner(System.in);
sc.useDelimiter("\n");
System.out.println("重定向输入内容:");
while(sc.hasNext())
{//将"RedirectInOut.java"文件的内容写入"out.txt"文件
System.out.println(sc.next());
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: