用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(),因此更容易识别整数/浮点数/字符串。
HUX布斯
慕神8447489
小怪兽爱吃肉
随时随地看视频慕课网APP
相关分类