java读写C语言二进制文件

我最近用java解析了一个C语言生成的二进制文件,各种折腾,终于是解析出来了。其实要注意的就是大小端转换,还有C语言有8字节补位操作可能。解析的时候,和C语言代码中设置的结构体长度不太相同,会有移位现象。字符串charsetName是“GBK”编码。总之,还得具体文件文件具体分析。下面是我自己写的读写方法,记录一下。

    /**
     * 写二进制文件,其中数据存储修改为小端存储
     * @param filePath
     */
    public static void writeBinaryFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            FileOutputStream out = new FileOutputStream(file);
            DataOutputStream dos = new DataOutputStream(out);

            byte[] itemBuf = new byte[120];
            dos.write(itemBuf, 0, 100);//写一个100byte的空内容
            itemBuf = copyByte("这是字符串");
            dos.write(itemBuf, 0, 40);//长度为40byte的字符串
            dos.writeBoolean(true);//boolean,1bit
            dos.writeShort(bytesToLittleEndianShort(short2Bytes((short) 36)));//short,2byte,转成byte数组之后,再转成小端存储
            dos.writeInt(bytesToLittleEndianInt(int2Bytes(3)));//int,4byte,转成byte数组之后,再转成小端存储
            dos.writeLong(bytesToLittleEndianLong(long2Bytes(123456789)));//long,8byte,转成byte数组之后,再转成小端存储

            dos.flush();
            dos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static byte[] copyByte(String str) throws UnsupportedEncodingException {
        byte[] tempByte = new byte[120];
        if (null == str || str.length() == 0) {
            return tempByte;
        }
        byte[] strByte = str.getBytes(charsetName);
        int length = strByte.length > 120 ? 120 : strByte.length;
        for (int i = 0; i < length; i++) {
            tempByte[i] = strByte[i];
        }
        return tempByte;
    }

上面是写的方法,主要就是用到FileOutputStream和DataOutputStream这两个类。读的方法也是类似的主要使用是对应的input类,FileInputStream和DataInputStream。

    /**
     * 读二进制文件,其中数据存转换成大端存储读取
     * @param filePath
     */
    public static void readBinaryFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            Log.i("tttt", "file not exist");
            return;
        }
        try {
            FileInputStream in = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(in);

            byte[] itemBuf = new byte[120];
            byte[] itemShortBuf = new byte[2];
            byte[] itemIntBuf = new byte[4];
            byte[] itemLongBuf = new byte[8];

            dis.read(itemBuf, 0, 100);
            String str = new String(itemBuf, 0, 100);
            System.out.println("空字符串:" + str);

            dis.read(itemBuf, 0, 40);
            String strName = new String(itemBuf, 0, 40, charsetName);//read方法读取一定长度之后,被读取的数据就从流中去掉了,所以下次读取仍然从 0开始
            System.out.println("字符串:" + strName.trim());

            boolean readBoolean = dis.readBoolean();
            System.out.println("readBoolean:" + readBoolean);

            dis.read(itemShortBuf, 0, 2);//读取2字节byte数组
            short readShort = bytesToBigEndianShort(itemShortBuf);//将2字节byte数字转成大端存储,返回short
            System.out.println("readShort:" + readShort);

            dis.read(itemIntBuf, 0, 4);//读取4字节byte数组
            int readInt = bytesToBigEndian(itemIntBuf);//将4字节byte数字转成大端存储,返回int
            System.out.println("readInt:" + readInt);

            dis.read(itemLongBuf, 0, 8);//读取8字节byte数组
            long readLong = bytesToBigEndianLong(itemLongBuf);//将8字节byte数字转成大端存储,返回long
            System.out.println("readLong:" + readLong);

            dis.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

读出来的结果如下:

空字符串因为没有trim(),所以打印出来是上面的样子,trim一下就是空了。

如果直接用大端存储,读写也就不用转换大小端了,会变的简单点。

    /**
     * 读二进制文件,其中数据直接读取
     * @param filePath
     */
    public static void readBinaryFile1(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            Log.i("tttt", "file not exist");
            return;
        }
        try {
            FileInputStream in = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(in);

            byte[] itemBuf = new byte[120];

            dis.read(itemBuf, 0, 100);
            String str = new String(itemBuf, 0, 100);
            System.out.println("空字符串:" + str);

            dis.read(itemBuf, 0, 40);//read方法读取一定长度之后,被读取的数据就从流中去掉了,所以下次读取仍然从 0开始
            String strName = new String(itemBuf, 0, 40, charsetName);
            System.out.println("字符串:" + strName.trim());

            boolean readBoolean = dis.readBoolean();
            System.out.println("readBoolean:" + readBoolean);

            short readShort = dis.readShort();
            System.out.println("readShort:" + readShort);

            int readInt = dis.readInt();
            System.out.println("readInt:" + readInt);

            long readLong = dis.readLong();
            System.out.println("readLong:" + readLong);

            dis.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写二进制文件,其中数据存储直接用大端模式
     * @param filePath
     */
    public static void writeBinaryFile1(String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            FileOutputStream out = new FileOutputStream(file);
            DataOutputStream dos = new DataOutputStream(out);

            byte[] itemBuf = new byte[120];
            dos.write(itemBuf, 0, 100);//写一个100byte的空内容
            itemBuf = copyByte("这是字符串");
            dos.write(itemBuf, 0, 40);//长度为40byte的字符串
            dos.writeBoolean(true);//boolean,1bit
            dos.writeShort(2);//short
            dos.writeInt(23);//int
            dos.writeLong(987654321);//long

            dos.flush();
            dos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

读取结果如下:

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了将二进制文件读入链表,你可以按照以下步骤进行操作: 1. 首先,你需要定义一个结构体来表示学生的信息,包括学号、姓名、性别、年龄和成绩等字段。 2. 然后,你需要创建一个链表结构,用来存储学生的信息。链表的每个节点都包含一个学生的结构体对象和指向下一个节点的指针。 3. 接下来,你需要打开二进制文件,以读取其中的数据。你可以使用C语言中的fopen函数打开文件,使用fread函数读取文件中的数据,并使用fclose函数关闭文件。 4. 在读取文件数据之前,你需要判断文件是否存在,如果不存在则创建一个空链表。如果文件已经存在,则需要将文件中的数据读取到链表中。 5. 当你读取文件中的学生信息后,需要将其插入到链表中的合适位置,按照总成绩从大到小的顺序进行插入。你可以通过比较当前学生的成绩与链表中已有学生的成绩来确定插入位置。 6. 最后,你可以选择是否继续从用户输入中读取更多的学生信息,如果用户选择继续,则重复步骤3-5,直到用户选择退出。 7. 当用户选择退出后,你可以将链表中的数据重新写入到二进制文件中。你可以使用fwrite函数将链表中的数据按照总成绩从大到小的顺序写入到文件中。 请注意,这只是一个概述,并不包含具体的代码实现。实际的代码可能需要进一步的细节处理和错误处理。同时,你还可以根据具体需求对代码进行修改和优化。希望对你有所帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [实验十 学生成绩管理(二进制文件读写)byHNU信息院2020小毕](https://blog.csdn.net/jiajia1as/article/details/111879722)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [高级java开发集合问题](https://download.csdn.net/download/tgh5330992/88227020)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值