Java ObjectOutputStream/ObjectInputStream的文件操作问题
我正在尝试使用ObjectOutputStream将两个对象写入一个文件。之后,我使用ObjectInputStream读取该文件。问题是,我只能读取文件中的第一个对象。当我用notepad++打开文件时,我可以看到其他对象的条目 这里是作者部分Java ObjectOutputStream/ObjectInputStream的文件操作问题,java,file,objectinputstream,objectoutputstream,Java,File,Objectinputstream,Objectoutputstream,我正在尝试使用ObjectOutputStream将两个对象写入一个文件。之后,我使用ObjectInputStream读取该文件。问题是,我只能读取文件中的第一个对象。当我用notepad++打开文件时,我可以看到其他对象的条目 这里是作者部分 public class FileProcess { private ObjectOutputStream output; private Accounts account; public FileProcess() {}
public class FileProcess {
private ObjectOutputStream output;
private Accounts account;
public FileProcess() {}
public void WriteObject(Accounts account) {
this.account = account;
openFile();
addRecords();
closeFile();
}
private void openFile() {
try {
output = new ObjectOutputStream(Files.newOutputStream(Paths.get("record_files.txt"),CREATE,APPEND));
}catch (Exception e) {
System.out.println("\nError opening file");
}
}
private void addRecords() {
try {
output.writeObject(account);
}
catch (Exception e) {
System.out.printf("Error writing file %s",e);
}
}
private void closeFile() {
try {
if(output != null)
output.close();
} catch (Exception e) {
System.out.println("\nError closing file");
}
}
}
和读者部分
abstract class User {
private String userID;
private int password;
private String position;
private ObjectInputStream input;
public User(String userID, int password, String position) {
this.userID = userID;
this.password = password;
this.position = position;
}
boolean signIn() {
boolean found_check = false;
openFile();
found_check = checkRecords();
closeFile();
return found_check;
}
private void closeFile() {
try {
if(input != null)
input.close();
} catch (Exception e) {
System.out.println("Error closing file");
}
}
private boolean checkRecords() {
try {
while(true) {
Accounts account = (Accounts) input.readObject();
System.out.printf("%s %d %s",account.getUserID(),account.getPassword(),account.getPosition());
}
}
catch (Exception e) {
System.out.println("\nError reading file");
return false;
}
return false;
}
private void openFile() {
try {
input = new ObjectInputStream(Files.newInputStream(Paths.get("record_files.txt")));
}catch (Exception e) {
System.out.println("Error opening file");
}
}
}
Accounts类实现可序列化
public class Accounts implements Serializable {
private String userID;
private int password;
private String position;
public Accounts(String userID, int password, String position) {
try {
this.userID = userID;
this.password = password;
this.position = position;
}
catch (Exception e) {
System.out.printf(e.toString());
}
}
}
您的代码引发以下异常:
java.io.streamcorruptedeException:无效类型代码:AC
这是通过添加
e.printStackTrace()发现的
到用户中的异常处理程序。checkRecords
您如何知道它只读取了一条记录?因为checkRecords
总是返回false,或者您看到控制台中打印了一行?我看到控制台中打印了一行