前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >字节流-文件输入流FileInputStream[基本使用]

字节流-文件输入流FileInputStream[基本使用]

作者头像
itze
发布2022-10-31 15:55:29
2950
发布2022-10-31 15:55:29
举报
文章被收录于专栏:IT者IT者
代码语言:javascript
复制
/**
     * @Author: www.itze.cn
     * @Date: 2020/9/24 10:29
     * @Email: 814565718@qq.com
     */
    /**
     * 读取一个文件,然后每10个字节换行
     *
     * @param fileName
     */
    public static void printHex(String fileName) {
        int b;
        int a = 1;
        try {
            //把文件作为字节流操作
            FileInputStream fis = new FileInputStream(fileName);
            while ((b = fis.read()) != -1) {  //每次只读一个字节
                //以16进制
                System.out.print(Integer.toHexString(b) + " ");
                if (a++ % 10 == 0) {  //每10个字节换行
                    System.out.println();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将一个文件读到byte数组中
     *
     * @param fileName
     */
    public static void printHexByByteArrays(String fileName) {
        try {
            //把文件作为字节流操作
            FileInputStream fis = new FileInputStream(fileName);
            byte[] bytes = new byte[10 * 1024]; //1024个字节=1KB 10*1024=10KB
            int i = 1;
            //把文件读到byte数组中,并且放入从0-bytes.length的位置,返回值read为读到的字节个数
            int read = fis.read(bytes, 0, bytes.length);
            for (int j = 0; j < read; j++) {  //这里只遍历读到个字节个数
                System.out.print(Integer.toHexString(bytes[j]) + " ");
                if (i++ % 10 == 0) {   //每10个字节换行
                    System.out.println();
                }
            }
            //当数组不够大的时候一次性无法读完,使用循环去读
            int readBteys;
            while ((readBteys = fis.read(bytes, 0, bytes.length)) != -1) {
                for (int j = 0; j < readBteys; j++) {
                    System.out.print(Integer.toHexString(bytes[j]) + " ");
                    if (i++ % 10 == 0) {  //每10个字节换行
                        System.out.println();
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020年9月24日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档