java-I/O File类(3)-FileInputStream/FileOutputStream

FileInputStream和FileOutputStream
节点流,用于从文件中读取或往文件中写入字节流。如果在构造FileOutputStream时,文件已经存在,则覆盖这个文件。

class StreamTest {
    public static void main(String[] args) throws Exception{
        //对文件的写入和对文件的读取
        FileOutputStream fos = new FileOutputStream("1.txt");
        //利用String对象的getBytes()获得字符数组
        fos.write("www.baidu.com".getBytes());
        fos.close();

        FileInputStream fis = new FileInputStream("1.txt");
        byte[] b = new byte[100];
        //读取文件内容的时候会返回读取的字节个数
        int length = fis.read(b);
        //利用String类的构造函数来读取有效字符
        System.out.println(new String(b,0,length));
        fis.close();
    }
}

结果:在工作空间同目录创建文件1.txt并写入baidu网址;会在控制台看到文件1.txt的内容即baidu网址。
BufferedInputStream和BufferedOutputStream
过滤流,需要使用已经存在的节点流来构造,提供带缓冲的读写,提高了读写的效率。

        //对文件的写入和对文件的读取
        FileOutputStream fos = new FileOutputStream("1.txt");
        //因为BufferedOutputStream构造函数要求是OutputStream对象,而FileOutputStream是OutputStream派生类
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //利用String对象的getBytes()获得字符数组
        bos.write("www.baidu.com".getBytes());
        //bos.close();在没有bos.flush()和没有关闭缓冲过滤流时候1.txt文件夹内容是空的,因为写操作写在了缓冲区。
        注意:在调用close()只需要调用缓冲过滤流的close()方法,即关闭后一个流。
class StreamTest {
    public static void main(String[] args) throws Exception{
        //对文件的写入和对文件的读取
        FileOutputStream fos = new FileOutputStream("1.txt");
        //因为BufferedOutputStream构造函数要求是OutputStream对象,而FileOutputStream是OutputStream派生类
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //利用String对象的getBytes()获得字符数组
        bos.write("www.baidu.com".getBytes());
        bos.close();

        FileInputStream fis = new FileInputStream("1.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        byte[] b = new byte[100];
        //读取文件内容的时候会返回读取的字节个数
        int length = bis.read(b);
        //利用String类的构造函数来读取有效字符
        System.out.println(new String(b,0,length));
        bis.close();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值