Java FileOutputStream 和 FileInputStream

在E盘新建一个文件s2.txt,内容如下

以下代码,可以打印出文件中的内容,

public static void main(String[] args) throws IOException {

        Properties prop = new Properties();    //定义 properties 对象
        FileInputStream fis = new FileInputStream("E:\\s2.txt");
        FileOutputStream fos = new FileOutputStream("E:\\s2.txt");

        prop.load(fis);
        System.out.println(prop);   //不可以打印出文件中的内容

        fis.close();
        fos.close();
    }

我们看到控制台输出的结果是这样的:

但是如果我们将代码稍微更改以下顺序:

public static void main(String[] args) throws IOException {

        Properties prop = new Properties();    //定义 properties 对象
        FileInputStream fis = new FileInputStream("E:\\s2.txt");
        FileOutputStream fos = new FileOutputStream("E:\\s2.txt");

        prop.load(fis);
        System.out.println(prop);   //不可以打印出文件中的内容

        fis.close();
        fos.close();
    }

在这里我们会发现,文件中的内容无法打印出来

在这里得到了一个空的集合

解决方案一 : 其实是在FileOutputStream fos = new FileOutputStream("E:\\s2.txt");这句代码中,将文件清空了,只要把FileOutputStream设置为追加模式就ok了,把上面这行代码改成FileOutputStream fos = new FileOutputStream("E:\\s2.txt",true); 问题解决.

解决方案二 : FileOutputStream fos = new FileOutputStream("E:\\s2.txt");把这行代码换一个位置,等FileInputStream读完了文本数据,再创建FileOutputStream,这样就算清空文件也不会受到影响了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值