我已经创建了一个名为random.txt
的文件。
我的工作是从该文件中获取输入,并使用ObjectOutputStream
将其存储到另一个文件中。
我已经为此编写了代码,但出现了以下错误:
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
at SortingNumberFile.main(SortingNumberFile.java:13)
我的代码是:
import java.util.*;
import java.io.*;
public class SortingNumberFile {
public static void main(String []args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\Programs\\AJP\\random.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
File f = new File("D:\\Programs\\AJP\\sort.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
int i;
while ((i=ois.readInt())!=-1) {
oos.writeInt(i);
System.out.println(i);
}
fis.close();
ois.close();
fos.close();
oos.close();
System.out.println("Done !!!");
}
}
答案 0 :(得分:2)
您最好在Java 7或更高版本中使用try with resources
来消除许多异常处理负担。解决方案之一可以是:
try (Scanner scanner = new Scanner(new File(inputPath));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputPath))) {
while (scanner.hasNextInt()) {
int a = scanner.nextInt();
bufferedWriter.write(String.valueOf(a) + "\n");
// seems you're using Windows, so it should be replace with \r\n perhaps;
System.out.println(a);
}
}
System.out.println("Done !!!");
测试数据(相同的输入格式和输出格式):
1
2
3
4