[英]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.