转载请标明出处:http://blog.csdn.net/xx326664162/article/details/51690162 文章出自:薛瑄的博客
你也可以查看我的其他同类文章,也会让你有一定的收货!
Java的标准输入/输出分别通过System.in和System.out来代表,在默认的情况下分别代表键盘和显示器
- 当程序通过System.in来获得输入时,实际上是通过键盘获得输入。
- 当程序通过System.out执行输出时,程序总是输出到屏幕。
在System类中提供了三个重定向标准输入/输出的方法
static void setErr(PrintStream err) 重定向“标准”错误输出流
static void setIn(InputStream in) 重定向“标准”输入流
static void setOut(PrintStream out)重定向“标准”输出流
下面程序通过重定向标准输出流:
将System.in的输入重定向到文件上,而不是在键盘上输入。
将System.out的输出重定向到文件输出,而不是在屏幕上输出。
package com.example;//: io/Redirecting.java
// Demonstrates standard I/O redirection.
import java.io.*;
public class Redirecting {
public static void main(String[] args)
throws IOException {
PrintStream console = System.out;
BufferedInputStream in = new BufferedInputStream(
new FileInputStream("Redirecting.java"));
PrintStream out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("test123.txt")));
System.setIn(in);
System.setOut(out);
System.setErr(out);
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String s;
while ((s = br.readLine()) != null)
System.out.println(s);
// 如果不使用重定向,使用下面的语句,也可达将内容写到指定文件中
// out.println(s);
out.close(); // Remember this!
System.setOut(console);
}
} ///:~
在第14行的test123.txt,会输出到与项目同级的目录中