gpt4 book ai didi

java - ObjectOutputStream/ObjectInputStream的文件操作问题

转载 作者:行者123 更新时间:2023-12-02 10:23:19 24 4
gpt4 key购买 nike

我正在尝试使用 ObjectOutputStream 将几个对象写入文件。之后,我使用 ObjectInputStream 读取该文件。问题是,我只能读取文件中的第一个对象。当我用 Notepad++ 打开文件时,我可以看到其他对象的条目。

这里是作者部分

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.StreamCorruptedException:无效类型代码:AC
There's a good question and answer here

这是通过将 e.printStackTrace(); 添加到 User.checkRecords 中的异常处理程序发现的。

关于java - ObjectOutputStream/ObjectInputStream的文件操作问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com