簡體   English   中英

讀取文件的前4個字節

[英]Read First 4 Bytes of File

我已經習慣了C#,但是我正在嘗試制作一個將前4個字節讀入數組的應用程序,但是我一直沒有成功。 我還需要反轉在Java中不知道的文件上的Array.Reverse(bytes); ,在C#中是Array.Reverse(bytes); 我嘗試將文件讀入Int32,但是由於某種原因,我無法從那里將其讀入數組。

像那樣 :

byte[] buffer = new byte[4];
InputStream is = new FileInputStream("somwhere.in.the.dark");
if (is.read(buffer) != buffer.length) { 
    // do something 
}
is.close();
// at this point, the buffer contains the 4 bytes...

您可以使用ByteBuffer更改字節序

FileChannel fc = new FileInputStream(filename).getChannel();
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteBuffer.nativeOrder()); // or whatever you want.
fc.read(bb);
bb.flip();
int n = bb.getInt();

反轉整數字節的簡單方法

int n = ...
int r = Integer.reverseByte(n);

類似地

long l = Long.reverseBytes(n);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM