Java读写文件的基本操作

最近做了一个和文件读写相关的需求,做的过程中发现IO流相关的知识总是忘记,,所以这里做一个读写文件基本操作的总结,如下所示,仅供参考~


1. 字节流读数据(一次读一个字节数据)

    @Test
    public void Test01() throws IOException {
        FileInputStream fis = new FileInputStream(filePath);
        int by;
        while ((by=fis.read())!=-1) {
            System.out.print((char)by);
        }
        fis.close();
    }

2. 字节流读数据(一次读一个字节数组数据)

@Test
public void Test02() throws IOException {
    FileInputStream fis = new FileInputStream(filePath);
    byte[] bys = new byte[1024]; //1024及其整数倍
    int len;
    while ((len=fis.read(bys))!=-1) {
        System.out.print(new String(bys,0,len));
    }
    fis.close();
}

3. 字节流写数据

    @Test
    public void Test03() throws IOException {
        FileOutputStream fos = new FileOutputStream(filePath);
//        fos.write(97);
        fos.write("abcdev".getBytes());
        fos.write("\r\n".getBytes()); //换行
        fos.write("abcdev".getBytes());
        fos.close();
    }

4. 字符流读数据

	@Test
    public void Test04() throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath));
        char[] chs = new char[1024];
        int len;
        while ((len = isr.read(chs)) != -1) {
            System.out.print(new String(chs, 0, len));
        }
        isr.close();
    }

5. 字符流写数据

@Test
public void Test05() throws IOException {
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath));
    osw.write("abcde", 1, 3);
    osw.close();
}

常用的IO流总结如下:
在这里插入图片描述


字节流和字符流其实在使用上很相似,只是字节流常用于操作普通的文本,而字符流优先操作图片视频等文件,而字节流又称为“万能流”。 同样缓冲流也很相似,主要的目的是为了提高操作效率!以上都是读写文件的部分基本操作,其他的方法也都类同,可以查阅对象的API对应使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值