Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从用Java编写的文件中读取C语言中的数据(二进制或文本)?_Java_C_File_Text Files_Binaryfiles - Fatal编程技术网

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

如何从用Java编写的文件中读取C语言中的数据(二进制或文本)?,java,c,file,text-files,binaryfiles,Java,C,File,Text Files,Binaryfiles,用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.putI

用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(){ 一,二,三; 文件*fp=fopen(“abc”,“r+”)

其输出为:

我不明白我看到了什么。有三个值,但都不是我写的。它们是内存位置还是垃圾值

Java以哪种格式写入文件。因为,C以我尝试使用ByteBuffer的底层平台的本机顺序读取。如果我使用DataOutputService,我认为Java以“BIG_ENDIAN”格式写入,而C可能无法读取正确的值

另外,在这种情况下,我如何写入和读取字符串。默认情况下,Java使用UTF-8,因此,我没有直接使用FileOutputStream,而是将它们转换为ASCII格式的字节,以便可以逐个字符读取它们。但是,没有显示输出。何时可以使用
fscanf(fp,“%s”,string)
(字符串是分配了足够内存的char数据类型变量)*



理想的解决方案是,Java能够以特定的顺序写入数据,而C能够使用
fscanf()
读取数据,因此更容易识别整数/浮点数/字符串。

我的Java有些生疏,但似乎您在文件中写入的是三个4字节的整数,顺序和机器字节顺序(所以可能是little endian)。这意味着您的文件应该有(十六进制):

但您的扫描希望看到的数字是以空格分隔的文本,例如(十六进制)

您可能应该使用类似于
fread()
,它不进行解析:

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

目标应该是
int[3]

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

这就是我所做的:

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格式的文本文件。另一点是,我们不必担心将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;
}
#包括
#包括
#包括
int main(){
文件*fp=fopen(“def.bin”,“r”);
一,二,三;
fscanf(fp、%d、&1);
fscanf(fp、%d、&2);
printf(“%d\n%d\n”,一,二);
整数指数;
fscanf(fp、%d、&index);
字符*字符串;
fscanf(fp,“%s”,字符串);
printf(“%d\n%s\n”,类号,字符串);
返回0;
}

我注意到字符串
char*
没有分配内存,仍然可以工作。

谢谢。但是,Java代码中也有解决方案吗?我问这个问题是因为,如果你不知道字符串的大小,很难识别字符串的结束位置。如果字符串后面有一个整数,我就不知道了,那该怎么办。@Tarunganti:那会这是一个不同的问题,但是-这看起来很简单:做与你所做的相反的事情。只是,然后使用从ByteBuffer中获取一个整数。很简单。我可能会含糊地问这个问题。如何使用Java编写并读入C以便我可以轻松地检测到整数、字符串或浮点?@Tarunmagni:如果给定的程序编写它是整数、字节、字符或字符数组(字符串?)的二进制表示形式,需要以与写入时完全相同的方式读取。在写入和读取这些数据时,必须遵循“约定”。向下的投票人能否解释为什么以及如何改进?
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
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);
        }
    }
}
#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;
}