java IO

IO流体系庞大,根据方向分为:输入流、输出流
根据对象分为:字节流、字符流


FileInputStream与FileOutputStream

这两个流,比较常见。用于文件的读写操作。同时他们继承与抽象类InputStream和OutputStream。

文件读到程序中

1、每次读取一个字节

 /**读取一个文件,以十六进制打印出来*/
    public static void printHex(String filename) throws IOException {

        int b;
        int i =1;
        FileInputStream inputStream = new FileInputStream(filename); //创建输入流对象
        while ((b=inputStream.read())!= -1){   //一次读取一个字节,读到-1结束
            System.out.print(Integer.toHexString(b)+ " ");
            /*if (i++%2 == 0)  //每行打印两个
                System.out.println();*/
        }
        inputStream.close();
    }

2、读取到数组缓冲区

 public static void printHexByBuf(String filename) throws IOException{

        //1、创建输入文件流
        FileInputStream in = new FileInputStream(filename);
        //2、定义buf数组,放文件字节
        byte[] buf = new byte[1024];

        //3.用read方法读到buf中,返回文件的字节个数
        int bytes = in.read(buf,0,buf.length);
        //4、数组长度是字节的个数
        for (int i =0; i<bytes;i++){
            System.out.println(buf[i]);
        }
    }

3、文件拷贝

/**s文件拷贝*/
    public static void copyFile(File srcFile ,File desFile) throws IOException{

        //1、判断源文件是否存在
        if (!srcFile.exists()){
            throw new IllegalArgumentException("文件"+ srcFile + "不存在");
        }
        //2、判断源文件是文件吗,目录就不复制
        if (!srcFile.isFile()){
            throw new IllegalArgumentException(srcFile + "不是文件");
        }
        //3、创建文件输入流,与输出流对象
        FileInputStream in = new FileInputStream(srcFile); //将文件读到程序中
        FileOutputStream out  = new FileOutputStream(desFile); //程序中的数据写出到文件中

        //4、创建字节数组,存放读取的文件
        byte[] buf = new byte[1024*6];

        int bytes =in.read(buf,0,buf.length); //读到buf缓存中
        out.write(buf,0,bytes); //写到文件输出流中
        
         //5、关闭流对象
        in.close();
        out.close();
    }

DataInputStream与DateOutputStream

是对File流的扩展,为了更好的支持多种数据类型的读写
/**
 * DataOutputStream/DataInputStream
 * 对流功能的扩展,支持更多类型是读写,
 * 原来只支持byte类型
 * */
    //利用DataOutputStream类,写文件
    public static void writeDataToFile(String filename) throws IOException{
        //1、创建数据输出流
        DataOutputStream out = new DataOutputStream(new FileOutputStream(filename)); /**需要File对象*/

        //2.利用DataOutputStream对象的write()实现向文件写多种数据类型
        out.writeInt(10);
        out.writeLong(10L);
        out.writeDouble(34.5);
        out.writeUTF("中国");
        out.close();
        out.close();
        IoUtils.printHex(filename);
    }

字节缓冲流

BufferedInputStream \ BufferedOutputStream (带缓冲的字节流)为IO提供带缓冲区的实现,提高了IO性能
比较三种拷贝文件的时间效率,利用创建数组空间最快,字节缓冲流其次,单个字节拷贝最慢。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值