我有一个功能,旨在将文本文件的内容写入二进制文件。当overwrite为true时,代码工作正常,但是当overwrite为false时,它在第80行停止(oldCount = binaryInput.readInt();)并抛出一个空异常。我是Java的新手,所以我可能会做一些明显的事情。这是堆栈跟踪:java.io.EOFException 在java.io.DataInputStream.readInt(未知来源) at java.io.ObjectInputStream $ BlockDataInputStream.readInt(Unknown Source) at java.io.ObjectInputStream.readInt(Unknown Source) 在Converter.fromText(Converter.java:80) 在Tron_Class.main(Tron_Class.java:19)
public static int fromText (String textRefference, String binaryRefference, boolean overwrite){
if(!(new File(binaryRefference).exists()))overwrite = true;
BufferedReader input;
ObjectOutputStream output;
ObjectInputStream binaryInput;
int count = 0;
try{
input = new BufferedReader(new FileReader(textRefference));
String[] data = null;
int oldCount = 0;
if(!overwrite){
binaryInput = new ObjectInputStream(new FileInputStream(binaryRefference));
oldCount = binaryInput.readInt();
data = new String[oldCount];
int i;
for(i = 0;i < oldCount; i++){
data[i] = binaryInput.readUTF();
}
}
output = new
ObjectOutputStream(new FileOutputStream(binaryRefference));
String sentinel = input.readLine();
String[] data2 = new String[1500];
while(!sentinel.equalsIgnoreCase("end")){
System.out.println(sentinel + " has been recorded");
data2[count] = sentinel;
sentinel = input.readLine();
count++;
}
if(!overwrite)count += oldCount;
output.writeInt(count);
if(!overwrite){
int i;
for(i = 0; i < oldCount;i++){
output.writeUTF(data[i]);
}
}
int i = 0;
for(; i < count;i++){
output.writeUTF(data2[i]);
}
output.close();
input.close();
}
catch(Exception e){
Scanner in = new Scanner(System.in);
System.out.println(e.getMessage());
System.out.println("\n hit ENTER to exit.");
in.nextLine();
System.exit(0);
}
return count;
}
答案 0 :(得分:0)
此循环不正确。
int i = 0;
for(; i < count;i++){
问题是count
是字符串的总数,而不仅仅是此data2
数组中的数字。一旦你尝试writeUTF(null)
,它就会爆炸。
更简单的解决方案是不首先修改count
,而是写
output.writeInt(oldCount + count);
然后上面的循环将有正确的count