zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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

文件字节输入 使用 基本 FileInputStream
2023-06-13 09:14:21 时间
/**
     * @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();
        }
    }