java IO 字节流最常用两种读写方式

java IO 字节流最常用两种读写方式

随笔记录

今天在看导入功能开发时顺便动手敲了一下Java io字节流读写的代码,感觉简单,但是深刻理解还是需要话功夫研究,也在博客中mark一下,便于温故知新

package com.gsww.jzfp.commons;


import java.io.*;

/**
 * Description:java IO 流学习
 */
public class JavaIODeamo {

    public static void main(String[] args) {
        File file =new File("D:\\copy_nginx.conf");
        try {
            //getFileByOutPutStream(file);
            getFileByBufferedOutPutStream(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 利用 字节流 读取文件、写入文件
     * @param file
     */
    private static void getFileByOutPutStream(File file) throws IOException {
        //读取文件
        InputStream in = new FileInputStream(new File("D:\\nginx.conf"));
        //写出文件
        //1、判断文件是否存在
        if(!file.exists()){
            file.createNewFile();
        }
        OutputStream out = new FileOutputStream(file);
        //2、定义输出字节长度
        byte[] bytes=new byte[2018];
        int len= -1;
        //3、循环输出
        while ((len = in.read(bytes,0,bytes.length))!=-1){
            //转换成字符串
            String str = new String(bytes,0,len,"GBK");
            System.out.println(str);
            //输出
            out.write(bytes,0,len);
        }

        out.flush();
        in.close();
        out.close();
    }

    /**
     * 利用 缓冲字节流 读取文件、写入文件
     * @param file
     */
    private static void getFileByBufferedOutPutStream(File file) throws IOException {
        //读取文件
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("D:\\nginx.conf")));

        //写出文件
        //1、判断文件是否存在
        if(!file.exists()){
            file.createNewFile();
        }
        //2、输出流
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));

        //定义字节长度
        byte[] bytes = new byte[2048];
        int len = -1;
        //循环写出
        while ((len = in.read(bytes, 0, bytes.length)) != -1) {
            //可以转换字符流
            String Str = new String(bytes, 0, len, "GBK");
            System.out.println(Str);
            //字节输出
            out.write(bytes,0,len);
        }
        out.flush();
        in.close();
        out.close();
    }

    
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值