[英]How to read binary file to binary characters java
我有一个二进制文件,我需要按照它们在二进制文件中的相同顺序读取并保存为字符或 0 和 1 的字符串。 我目前能够读取二进制文件,但无法获取 0 和 1。 这是我目前使用的代码:
public void read()
{
try
{
byte[] buffer = new byte[(int)infile.length()];
FileInputStream inputStream = new FileInputStream(infile);
int total = 0;
int nRead = 0;
while((nRead = inputStream.read(buffer)) != -1)
{
System.out.println(new String(buffer));
total += nRead;
}
inputStream.close();
System.out.println(total);
}
catch(FileNotFoundException ex)
{
System.out.println("File not found.");
}
catch(IOException ex)
{
System.out.println(ex);
}
}
以及使用二进制文件运行它的输出:
�, �¨Ã �¨ÊÃ
�!Cˇ¯åaÃ!Dˇ¸åÇÃ�"( ≠EÃ!J�H���û�������
����������������������������������������������������������������������������������������
156
谢谢你提供的所有帮助。
在 Java 中查看String 到二进制输出。 基本上,您需要获取您的字符串,将其转换为字节数组,然后将每个字节作为二进制字符串打印出来。
不是将字节直接转换为字符然后打印出来,而是将每个字节转换为二进制字符串并打印出来。 换句话说,替换
System.out.println(new String(buffer));
和
for (int i = 0; i<nRead; i++) {
String bin=Integer.toBinaryString(0xFF & buffer[i] | 0x100).substring(1);
System.out.println(bin);
}
请注意,每个字节的位都是按大端顺序打印的。 没有办法知道位实际上是否按此顺序存储在磁盘上。
使用JBBP这样的操作会很容易
public static final void main(final String ... args) throws Exception {
try (InputStream inStream = ClassLoader.getSystemClassLoader().getResourceAsStream("somefile.txt")) {
class Bits { @Bin(type = BinType.BIT_ARRAY) byte [] bits; }
for(final byte b : JBBPParser.prepare("bit [_] bits;",JBBPBitOrder.MSB0).parse(inStream).mapTo(Bits.class).bits)
System.out.print(b != 0 ? "1" : "0");
}
}
但它不会处理大文件,因为解析的数据会在操作过程中缓存在内存中
即使此响应是用 C 语言编写的,您也可以使用 JNI 从 Java 程序本机访问它。
由于它们是二进制格式,您将无法阅读。 我会这样做。
fstream fs;
int value; //Since you are reading bytes, change accordingly.
fs.open( fileName, is.in | is.binary );
fs.read((char *) &value, sizeof(int));
while(!fs.eof())
{
//Print or do something with value
fs.read((char *) &value, sizeof(long));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.