为了账号安全,请及时绑定邮箱和手机立即绑定

如何从用 Java 编写的文件中读取 C 中的数据(二进制或文本)?

如何从用 Java 编写的文件中读取 C 中的数据(二进制或文本)?

HUX布斯 2022-11-02 16:09:40
用Java编写:File file = new File("abc");try(FileOutputStream fos = new FileOutputStream(file)) {    FileChannel outChannel = fos.getChannel();    ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES*3).order(ByteOrder.nativeOrder());    buffer.putInt(154);    buffer.putint(98);    buffer.putInt(6);    outChannel.write(buffer);    IntStream.rangeClosed(1,3).forEach((iter) -> {        String reqString = (Integer.toString(iter) + "_string");        byte[] bytes = reqString.getBytes(Charset.forName("US-ASCII"));        ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length).order(ByteOrder.nativeOrder());        byteBuffer.put(bytes);        try {            outChannel.write(byteBuffer);        }        catch(IOException ex) {            ex.printStackTrace();        }    });}   catch(IOException ex) {    ex.printStackTrace();}用 C 读: int main() { int one,two,three; 文件 *fp = fopen("abc","r+");fscanf(fp,"%d",&one);fscanf(fp,"%d",&two);fscanf(fp,"%d",&three);printf("%d %d %d",one,two,three);char ch;fread(&ch,sizeof(char),1,fp);while(ch!= '\0') {    printf("%c",ch);    fread(&ch,sizeof(char),1,fp);} return 0;}输出为:我不明白我看到了什么。有三个值,没有一个是我写的。它们是内存位置吗?还是垃圾值?Java以哪种格式写入文件。因为,C 以底层平台的本机顺序读取,所以我尝试使用 ByteBuffer。如果我使用 DataOutputService,我认为 Java 以“BIG_ENDIAN”格式写入,而 C 可能无法读取正确的值。另外,在这种情况下如何读写字符串。Java,默认情况下使用 UTF-8,因此,我没有直接使用 FileOutputStream,而是将它们转换为 ASCII 格式的字节,以便我可以逐个字符地读取它们。但是,没有显示输出。我什么时候可以使用fscanf(fp,"%s",string) (字符串是分配了足够内存的 char 数据类型变量)*?理想的解决方案是 Java 能够以特定顺序写入数据,而 C 能够使用 读取它fscanf(),因此更容易识别整数/浮点数/字符串。
查看完整描述

2 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

我的 Java 有点生疏,但看起来你写入文件的内容是三个 4 字节整数,按顺序和机器字节顺序(所以可能是小端序)。这意味着您的文件应该具有(十六进制):

9a 00 00 00 62 00 00 00 06 00 00 00

但是您的扫描预计会将数字视为以空格分隔的文本,例如(以十六进制表示)

31 35 34 20 39 38 20 36 0a

你可能应该使用类似的东西fread(),它不做解析:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

并且目标应该是类似的地址int[3]


查看完整回答
反对 回复 2022-11-02
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

我知道fscanf读取一个字符流,然后根据给定的格式对其进行解析。这意味着我们应该以 C 支持的字符格式用 Java 编写文件。


这就是我所做的:


Java代码:


package scratchpad;


import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.nio.charset.StandardCharsets;

import java.util.logging.Level;

import java.util.logging.Logger;


public class WriteClass {

    void writeFunction() {

        File defgFile = new File("/home/thor/Documents/ScratchPad/def.bin");

        try(FileOutputStream fos = new FileOutputStream(defgFile)){

            BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(fos,StandardCharsets.US_ASCII));

            bos.write(Integer.toString(123));

            bos.newLine();

            bos.write(Integer.toString(96));

            bos.newLine();

            bos.write(Integer.toString(1));

            bos.newLine();

            bos.write("Water");

            bos.newLine();

            bos.write(Integer.toString(2));

            bos.newLine();

            bos.write("Forest");

            bos.newLine();


            bos.flush();

            bos.close();

        }

        catch(IOException ex) {

            Logger.getLogger(WriteClass.class.getName()).log(Level.SEVERE,"Can't open a new file",ex);

        }

    }

}

需要注意的重要一点是,我曾经OutputStreamWriter以 ASCII 格式编写文本文件。另一点是我们不必担心ByteOrder将 ASCII 值写入文件的位置。似乎Java正在处理它。


独立于平台的bos.newLine()方式来编写一个新行。 bos.flush()是强制性的,否则数据将不会被写入。


C代码:


#include <stdio.h>

#include <stdlib.h>

#include <math.h>   


int main() {


    FILE *fp = fopen("def.bin","r");

    int one,two,three;

    fscanf(fp,"%d",&one);

    fscanf(fp,"%d",&two);

    printf("%d\n%d\n",one,two);


    int index;

    fscanf(fp,"%d",&index);

    char* string;

    fscanf(fp,"%s",string); 

    printf("%d\n%s\n",classno,string);

    return 0;

}

我注意到字符串char*没有分配内存并且仍然有效。


查看完整回答
反对 回复 2022-11-02
  • 2 回答
  • 0 关注
  • 137 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信