我已经阅读了我在网络上找到的任何页面,但没有一个适合我。
我有一个用 C 代码创建的二进制文件。我还有这个二进制文件的 C 阅读器。我需要为这个二进制文件编写 java 阅读器。
在 C 代码中,以下命令读取一个大小为 'b * max_w' 的字符串和一个字符。
fscanf(f, "%s%c", &vocab[b * max_w], &ch);
在java中我读取了二进制文件,
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bin = new BufferedInputStream(fis);
然后读取Bytes并将其转换为字符串。
for(int j = 0; j < 200; j++) {
int size = 2; // char is 2 bytes
byte[] tempId3 = new byte[size];
bin.read(tempId3, 0, size);
String id3 = new String ( tempId3 );
System.out.println( " id = " + id3 );
}
但是输出是一堆废话。难道我做错了什么?我可以做得更好吗?
编辑: 来自 here 的工作 C 代码片段从是:
fscanf(f, "%lld", &words);
fscanf(f, "%lld", &size);
vocab = (char *)malloc((long long)words * max_w * sizeof(char));
for (a = 0; a < N; a++) bestw[a] = (char *)malloc(max_size * sizeof(char));
这是我的:
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bin = new BufferedInputStream(fis);
int length = 1;
System.out.println("1st: ");
byte[] tempId = new byte[8];
bin.read(tempId, 0, 8);
String id = new String ( tempId, "US-ASCII" );
System.out.println( " out = " + id );
System.out.println("2nd: ");
int size1 = 8;
byte[] tempId2 = new byte[size1];
bin.read(tempId2, 0, size1);
String id2 = new String ( tempId2, "US-ASCII");
System.out.println( " out = " + id2 );
for(int j = 0; j < 20; j++) {
int size = 2;
byte[] tempId3 = new byte[size];
bin.read(tempId3, 0, size);
String id3 = new String ( tempId3, "US-ASCII" );
System.out.println( " out = " + id3 );
}
我看到的输出如下;除了前两个“长”数字外,其余都是废话(应该是字符)。
附言。 C代码是here (第44-60行是读取二进制文件的部分)
最佳答案
可能正在使用 Reader 就可以得到你需要的东西?使用 InputStream 读取二进制数据,Reader 读取字符串。
关于java - Java从二进制文件中读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21381420/