如何从文件中读取数字?当我使用 readInt 方法时,我得到一个很大的数字,并且它不等于文件中的数字。如何解决?
扫描仪不是一个好主意,因为文件包含超过 10 亿个数字,这将需要很长时间。
这是一个文本文件。该文件包含除以空格符号的数字。例如(test.txt)
1 2 4 -4004 15458 8876
public static void readByMemoryMappedFile(int buffer[], String filename) throws IOException {
int count = 0;
RandomAccessFile raf = new RandomAccessFile(filename, "r");
try {
MappedByteBuffer mapFile = raf.getChannel().map(MapMode.READ_ONLY, 0, raf.length());
StringBuilder b = new StringBuilder();
try {
while (mapFile.hasRemaining()) {
byte read = mapFile.get();
if (read == ' ' && b.length() > 0) {
buffer[count++] = mapFile.getInt();//Integer.parseInt(b.toString());
b.delete(0, b.length());
} else {
b.append((char) read);
}
}
} catch (BufferUnderflowException e) {
// Всё, файл закончился
}
if (b.length() > 0) {
buffer[count++] = Integer.parseInt(b.toString());
}
} finally {
raf.close();
}
}
So, I attached a report:
```none
// operation: time
reading: 39719 // t0
reading: 28297 // t1
reading: 56719 // t2
reading: 125735 // t3
reading: 199000 // t4
t0 < t1 < t2 < t3 < t4
如何更改我的程序的行为:t0 ~ t1 ~ t2 ~ t3 ~ t4?
最佳答案
如果您的数字存储为文本,则 readInt() 将不起作用。您必须解析该文件,这是唯一的方法。
关于java - 随机访问文件 readInt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4337485/