I/O流常用读写方式

I/O流的读写是java SE中的一块重要内容,下面是我总结的几种读写方式,在java7之前流的读写需要手动关闭流,但根据新特性现在只需要将所用到的流放入try的小括号内就可以了;

public class Dome1{
    public static void main(String[] args) {
        File file1 = Paths.get("D:", "test.txt" ).toFile();
        File file2 = Paths.get("D:", "test2.txt").toFile();
        try(FileInputStream in = new FileInputStream(file1);
            FileOutputStream out = new FileOutputStream(file2)
        ){
            int len = -1;
            byte[] buff = new byte[1024];
            while((len = in.read(buff))!=-1){
                out.write(buff,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

字符流和字节流的方法一致,不同点在于处理的文件类型不同,以及字节流不涉及缓冲区,字符流则是将数据先存入缓冲区然后再写入文件

public class Dome2 {
    public static void main(String[] args) {
        File file1 = Paths.get("D:", "test.txt").toFile();
        File file2 = Paths.get("D:", "test2.txt").toFile();
        try (BufferedReader in = new BufferedReader(new FileReader(file1));
             BufferedWriter out = new BufferedWriter(new FileWriter(file2))
        ) {
            //通过缓冲的方式进行高效读写
            String len = null;
            while((len = in.readLine())!=null){
                out.write(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

字符流和字节流之间可以进行转换,在转换时可以选择编码格式

class Dome3{
    public static void main(String[] args) {
        File file1 = Paths.get("D:", "test.txt").toFile();
        Charset charset = Charset.forName("UTF-8");
        try (FileInputStream in  = new FileInputStream(file1);
             InputStreamReader toReader = new InputStreamReader(in,charset);
             BufferedReader reader = new BufferedReader(toReader)
        ){
            String len = null;
            while ((len=reader.readLine())!=null){
                System.out.println(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值