[英]java: read large binary file
我需要讀出一個包含500000001二進制文件的給定大文件。 之后,我必須將它們轉換為ASCII。
嘗試在大型數組中存儲二進制文件時發生“我的問題”。 我在數組ioBuf的定義中得到警告:
“ int類型的字面量16000000032超出范圍。”
我不知道如何保存這些數字以便與他們合作! 有想法嗎?
這是我的代碼:
public byte[] read(){
try{
BufferedInputStream in = new BufferedInputStream(new FileInputStream("data.dat"));
ByteArrayOutputStream bs = new ByteArrayOutputStream();
BufferedOutputStream out = new BufferedOutputStream(bs);
byte[] ioBuf = new byte[16000000032];
int bytesRead;
while ((bytesRead = in.read(ioBuf)) != -1){
out.write(ioBuf, 0, bytesRead);
}
out.close();
in.close();
return bs.toByteArray();
}
數組的最大索引為Integer.MAX_VALUE
並且16000000032
大於Integer.MAX_VALUE
Integer.MAX_VALUE = 2^31-1 = 2147483647
2147483647 < 16000000032
您可以通過檢查陣列是否已滿並創建另一個並繼續閱讀來克服此問題。 但是我不確定您的方法是否是執行此操作的最佳方法。 byte [Integer_MAX_VALUE]很大;)也許您可以將輸入文件分成較小的塊進行處理。
編輯:這是您可以讀取文件的單個int的方式。 您可以將緩沖區的大小調整為要讀取的數據量。 但是您嘗試一次讀取整個文件。
//Allocate buffer with 4byte = 32bit = Integer.SIZE
byte[] ioBuf = new byte[4];
int bytesRead;
while ((bytesRead = in.read(ioBuf)) != -1){
//if bytesRead == 4 you read 1 int
//do your stuff
}
long
常量。 但是,如另一個答案中所述,您不能聲明那么大的數組。 我從頭開始取得了一些進步! 但是我仍然有問題。
我的想法是讀取前32個字節,將它們轉換為int數。 然后是接下來的32個字節,等等。不幸的是,我只是第一個字節,不知道如何進行。
我發現了以下將這些數字轉換為int的方法:
public static int byteArrayToInt(byte[] b){
final ByteBuffer bb = ByteBuffer.wrap(b);
bb.order(ByteOrder.LITTLE_ENDIAN);
return bb.getInt();
}
所以現在我有:
BufferedInputStream in=null;
byte[] buf = new byte[32];
try {
in = new BufferedInputStream(new FileInputStream("ndata.dat"));
in.read(buf);
System.out.println(byteArrayToInt(buf));
in.close();
} catch (IOException e) {
System.out.println("error while reading ndata.dat file");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.