我正在尝试使用冒泡排序(我知道效率非常低)来排序某些数据,但是我的代码表现得非常奇怪,在外部while循环的926次传递之后,抛出了IOException,这与输入的数据,我已经检查过,它似乎与可用的内存量无关,代码和异常如下:
public static void sort(String f1, String f2) throws FileNotFoundException, IOException {
RandomAccessFile reader = new RandomAccessFile(f1,"rw");
RandomAccessFile writer = new RandomAccessFile(f1,"rw");
// start the bubble sort
int limit = (int) reader.length()/4;
while (limit>1) {
DataOutputStream writerstream = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(writer.getFD())));
DataInputStream readerstream = new DataInputStream(
new BufferedInputStream(new FileInputStream(reader.getFD())));
// the first value, a is the first value in the file
int a = readerstream.readInt();
int myfilepointer = 4;
// this flag is used to stop passing through when correct order is detected
boolean setpass = false;
// pass through the file
while (myfilepointer<limit*4) {
// the second value, b is the next value in the file
//System.out.println(myfilepointer);
int b = readerstream.readInt();
myfilepointer += 4;
// test if a and b are in the correct way around
// if wrong way around then b is written and the next a value is the same as before
if (a>b) { writerstream.writeInt(b); setpass = false; }
// if the correct way about then a is written and the next a value is the same as the previous b value
else { writerstream.writeInt(a); a = b; }
}
// this last value is the a value of exiting the while loop
writerstream.writeInt(a);
// write the new data to the file
writerstream.flush();
writer.seek(0);
reader.seek(0);
// if there was no swaps then the order is correct so exit loop
if (setpass == true) break;
limit -= 1;
}
}
,抛出的异常在
之下Exception in thread "main" java.io.IOException: Read error
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at java.io.DataInputStream.readInt(Unknown Source)
at uk.ac.cam.hh360.fjava.tick0.ExternalSort.sort(ExternalSort.java:48)
at uk.ac.cam.hh360.fjava.tick0.ExternalSort.main(ExternalSort.java:119)
答案 0 :(得分:1)
一个潜在的问题是你没有关闭在外循环中打开的流。
答案 1 :(得分:0)
您正在写入您正在阅读的同一个文件。因此,只要您将第一个整数写入编写器流,文件的内容就会被您编写的内容替换。由于你使用的是BufferedOutputStream,它实际上可能比你第一次写作时要晚。
您应该读取内存中的所有整数,关闭输入流,对内存中的整数进行排序,然后将所有整数写入文件。
我不明白你为什么要使用随机访问文件来获取文件描述符和文件上的开放流。您要么随机访问它,要么想要使用流访问它。但你不能两者兼顾。