【发布时间】:2018-09-13 21:52:39
【问题描述】:
正如标题所示,我想将对象写入文件而不覆盖同一个文件。 问题是,当我尝试将对象写入文件时,我收到以下消息:
"org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; 文件过早结束。继续..."
然后没有任何东西进入文件。如果我尝试在其他类型的文件(如 .ser)中进行可序列化,我会收到一条错误消息,指出无法写入文件。
package application.library.crud.kvlth;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Create {
private static XMLEncoder output;
private static XMLDecoder inpt;
public static void main(String[] args) throws IOException {
openFile();
addRecords();
closeFile();
}
public static void openFile() {
try {
output = new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream("library.xml")));
} catch (IOException ioException) {
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
public static void addRecords() throws IOException {
inpt = new XMLDecoder(
new BufferedInputStream(
new FileInputStream("library.xml")));
ArrayList<Book> books;
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter ISBN number, Author's name, Book's Title.",
"Enter end-of-file indicator to end input.");
while (input.hasNext()) {
try {
Book record = new Book(input.nextLine(),
input.nextLine(), input.nextLine());
books = (ArrayList<Book>) inpt.readObject(); /*here
at my IDE (Intellij) it shows me the following
message: "Unchecked cast: 'java.lang.Object' to
'java.util.ArrayList'"*/
inpt.close();
books.add(record);
output.writeObject(books);
} catch (NullPointerException e){
e.getStackTrace();
} catch (ArrayIndexOutOfBoundsException arrayExc){
}
System.out.println("? ");
}
}
public static void closeFile() {
if (output != null)
output.close();
}
}
This is what it shows to me. It continues running but never write to the file.
【问题讨论】:
-
当您尝试读取文件时是否收到 SAXParseException?可能是您的 library.xml 文件为空或格式错误。理想情况下,您应该将文件读取和写入逻辑从输入循环中分离出来。您尚未展示如何打开
output进行写作,将其包括在内会很有帮助。 -
嘿@Geoff 谢谢你的答案。我很感激所以我编辑了帖子并包含了整个代码。在我将对象发送到填充后,我立即得到 SAXParseException,然后它向我显示了消息。应用程序继续运行,但它从不写入文件。