java读取二进制文件

别的都不需要,只要把文件中110h-22Fh字节中的ASCII字符串中的数字提取出来赋给int型或者float型变量就行了。比如这个图中,我需要这个0.009313赋值给float型变量 a ,该怎么做。这个二进制文件我可以提供。

思路:按照字节读取文件到缓冲,然后对文件内容进行处理。

代码如下:


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();
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-02-16
Java读取二进制文件,以字节为单位进行读取,还可读取图片、音乐文件、视频文件等,
在Java中,提供了四种类来对文件进行操作,分别是InputStream OutputStream Reader Writer ,前两种是对字节流的操作,后两种则是对字符流的操作。
示例代码如下:
public static void readFileByBytes(String fileName){
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("一次读一个");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
第2个回答  2014-02-28
提供下文件!