Java讀取二進制文件,以字節爲單位進行讀取,還可讀取圖片、音樂文件、視頻文件等,
在Java中,提供了四種類來對文件進行操作,分別是InputStream OutputStream Reader Writer ,前兩種是對字節流的操作,後兩種則是對字符流的操作。
示例代碼如下:
/**
* 讀取固件文件
*/
private void readFirmware(String fileName){
File file = new File(Const.baseDir + fileName);
int i=0;
try {
System.out.println("一次讀一個");
// 一次讀一個字節
InputStream in = new FileInputStream(file);
int temp_byte;
while ((temp_byte = in.read()) != -1) {
System.out.print(HexUtil.decToHex(temp_byte).toUpperCase() + " ");//System.out.write(temp_byte);write是源內容,print是字節碼
if (i++ == 35){
System.out.println();
i=0;
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
或者(下面不對的。。。)
思路:按照字節讀取文件到緩衝,然後對文件內容進行處理。
代碼如下:
public static void readFile() throws IOException{
RandomAccessFile f = new RandomAccessFile("test.txt", "r");
byte[] b = new byte[(int)f.length()];
//將文件按照字節方式讀入到字節緩存中
f.read(b);
//將字節轉換爲utf-8 格式的字符串
String input = new String(b, "utf-8");
//可以匹配到所有的數字
Pattern pattern = Pattern.compile("\\d+(\\.\\d+)?");
Matcher match = pattern.matcher(input);
while(match.find()) {
//match.group(0)即爲你想獲取的數據
System.out.println(match.group(0));
}
f.close();
}