Java 中 RandomAccessFile 类读取 txt 中数字
public static void readAccess() throws Exception {
String filename = "D:/file_sum/2.txt";
RandomAccessFile raf = new RandomAccessFile(filename, "rw");
int len = 0;
int seek = 0;
int index = 0;
while ((len = raf.read()) != -1) {
char ch = (char) len;
if (ch >= '0' && ch <= '9') {
index ++;
}
if (ch == ' ') {
raf.seek(seek);
byte[] buff = new byte[index + 1];
raf.read(buff, 0, buff.length);
System.out.println(new String(buff).trim());
seek += (index + 1);
index = 0;
}
}
if (index > 0) {
raf.seek(seek);
byte[] buff = new byte[index + 1];
raf.read(buff, 0, buff.length);
System.out.println(new String(buff).trim());
}
raf.close();
}
输出结果: