标准I/O重导向
Java不但提供了标准的I/O:System.in,System.out和System.err,也提供了对标准输入、标准输出、标准错误输出等I/O进行重导向。
在Java的System class中提供了以下几个静态函数实现了标准I/O的重导向:
public static void setIn(InputStream in);
将标准输入重导向为参数InputStream指定的输入流。
public static void setOut(PrintStream out);
将标准输出重导向为参数PrintStream指定的输出流。
public static void setErr(PrintStream err);
将标准错误输出重导向为参数PrintStream指定的输出流。
标准输出和标准错误输出默认输出到屏幕,为了以示和标准错误输出的区别,现将标准输出指向另一个文件,同时将标准输入也重定向到文件。程序如下:
import java.io.*;
public class ErrRedirecting
{
public ErrRedirecting()
{
}
public static void main(String[] args) throws IOException
{
//标准输出重导向的文件
String outFileName = "out.txt";
//标准输入重导向的文件
String inFileName = "in.txt";
//生成标准输入重导向的InputStream
BufferedInputStream in =
new BufferedInputStream(
new FileInputStream(inFileName));
//生成标准输出重导向的PrintStream
PrintStream out =
new PrintStream(
new BufferedOutputStream(
new FileOutputStream(outFileName)));
//标准输入输出的重导向
System.setIn(in);
System.setErr(out);
//从重导向的标准输入中读取数据到BufferedReader中
BufferedReader reader =
new BufferedReader(
new InputStreamReader(System.in));
String line;
//每次从BufferedReader读取一行数据并输出到重导向的输出文件
while ( (line = reader.readLine()) != null)
System.out.println(line);
//关闭
out.close();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.