![](/img/trans.png)
[英]Who is better in performance filechannel or RandomAccessFile for reading and writing?
[英]randomAccessFile method not writing or reading ints?
我有两种方法,一种是将10个整数写入randomAccessFile,另一种是读取10个整数。 我相信writer方法无法正常运行。
这是我写入随机文件的方法:
try{
RandomAccessFile file = new RandomAccessFile(nextPath, "rw");
System.out.println("Writing these ints to file");
file.seek(0);
// here I loop 10 times and write the int at position i
for (int i = 0; i < 10; i++)
{
file.seek(i);
toAdd = randInt(1,10);
file.writeInt(toAdd);
System.out.printf(toAdd + " ");
}
file.seek(0);
System.out.println("");
}catch(IOException ex){
System.out.println("Error");
System.exit(0);}
这是我读取int的方法:
public int[] readRandom()
{
System.out.println("Unsorted ints found in random file:");
int[] randomInts = new int[10];
try{
RandomAccessFile file = new RandomAccessFile(nextPath, "rw");
file.seek(0);
// here I loop 10 times, and read the Int at position i
for(int i = 0; i < 10; i++)
{
file.seek(i);
randomInts[i] = file.readInt();
System.out.printf(randomInts[i] + " ");
}
file.seek(0);
System.out.println("");
}catch(IOException exc){
System.out.println("Error reading ints");
System.exit(0);}
return randomInts;
}
这是我的输出:为什么只读取最后一个int?
Writing these ints to file
1 4 5 6 2 4 10 6 5 5
Unsorted ints found in random file:
0 0 0 0 0 0 0 0 0 5
在执行file.seek(i)时,您错过了重要的一点。 seek()方法将查找您提供的字节位置,并且将要查找的位置增加1。但是,当您将整数写入文件时,它将为每个整数写入4个字节。 你的柜台应该是这样
for (int i = 0; i < 10; i++) {
file.seek(i*4);
toAdd = randInt(1,10);
file.writeInt(toAdd);
System.out.printf(toAdd + " ");
}
显然,对于阅读,您可以执行此操作
for (int i = 0; i < 10; i++)
{
file.seek(i*4);
randomInts[i] = file.readInt();
System.out.printf(randomInts[i] + " ");
}
为什么要使用RandomAccessFile
执行顺序写入和顺序读取? 它违背了这个阶级的目的。
此外,您不应震惊捕获的异常,而应记录或跟踪它们。
关于您的意外结果,这是由不必要的seek()
调用引起的。 您不需要在每次读取或写入操作时都调用seek()
,因为readInt()
和writeInt()
可使光标前进。
我已经简化了示例代码以强调重要部分:
public void write() {
try {
RandomAccessFile file = new RandomAccessFile("temp.txt", "rw");
System.out.println("Writing these ints to file");
file.seek(0);
for (int i = 0; i < 10; i++) {
file.writeInt(i);
System.out.printf(i + " ");
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(0);
}
}
public int[] readRandom() {
System.out.println("Unsorted ints found in random file:");
int[] randomInts = new int[10];
try {
RandomAccessFile file = new RandomAccessFile("temp.txt", "rw");
long filePointer = file.getFilePointer();
file.seek(0);
for (int i=0; i<10; i++){
randomInts[i] = file.readInt();
System.out.printf(randomInts[i] + " ");
}
} catch (IOException ex) {
ex.printStackTrace();
System.exit(0);
}
return randomInts;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.