先将一个基本的关系图放在这里:
图片来源
将控制台内容输出到文件
PrintStream
从前面图中,处于流的继承包装的叶子端。(功能较全面)
PrintStream需要注意
- PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。【此时换为printWriter】
- PrintStream 永远不会抛出 IOException。
例子1
效果: 将控制台输出内容,输出到文件中。
- 原来的流导向是输出窗口,因为替换,内容会出现在文件中,但是不会出现在控制台窗口之中。
代码实例:
public class PrintInFileTest {
public static void main(String[] args) {
// test.
printInfile();
}
protected static void printInfile() {
String path = "test/out.txt";
try {
// 1.创建输出的文件。
File out = new File(path);
if (!out.exists()) {
out.createNewFile();
}
// 2.将文件路径传给输出流。
PrintStream print = new PrintStream(out.getAbsolutePath());
// 3.为系统的输出制定流。该流的导向是我们的文件。【关键】
System.setOut(print);
//4.进行输出测试。
System.out.println("i am in the file !!!");
} catch (Exception e) {
}
}
}
例子2
效果: 将错误信息打印到文件中
- 与上面控制台输出类似,我们通过设置异常的打印的参数,从而将信息输出定位到我们的文件中。
代码实例:
public class ExceptionInFileTest {
public static void main(String[] args) throws IOException {
// test.
printInfile();
}
protected static void printInfile() throws IOException {
String path = "test/out.txt";
try {
throw new Exception("mistakes !!!");
} catch (Exception e) {
File out = new File(path);
if (!out.exists()) {
out.createNewFile();
}
PrintStream print = new PrintStream(out.getAbsolutePath());
//e对象中是拥有一个输出流的,这里我们将其设置为了** 我们的IO流 **。
e.printStackTrace(print);
}
}
}