代码如下:
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()
}
Java读取二进制文件,以字节为单位进行读取,还可读取图片、音乐文件、视频文件等,在Java中,提供了四种类来对文件进行操作,分别是InputStream OutputStream Reader Writer ,前两种是对字节流的操作,后两种则是对字符流的操作。示例代码如下:public static void read()FileByBytes(String fileName){ File file = new File(fileName)InputStream in = nulltry { System.out.println("一次读一个")// 一次读一个字节 in = new FileInputStream(file)int tempbytewhile ((tempbyte = in.read()) != -1) { System.out.write(tempbyte)} in.close()} catch (IOException e) { e.printStackTrace()return}