java IO -- 输出到文件

本文介绍如何使用Java将控制台输出和错误信息重定向到文件中,包括使用PrintStream和异常跟踪的方法。


先将一个基本的关系图放在这里:

这里写图片描述
图片来源

将控制台内容输出到文件

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);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值