gpt4 book ai didi

java - 无法在目标文件中存储和加载数组列表

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:47 25 4
gpt4 key购买 nike

我正在尝试存储 Aluno 类型的对象:

public class Aluno implements Serializable{
String nome;
String estado; //licenciatura ou mestrado
float montanteMax;
public Aluno(String nome, String estado, float montanteMax) {
this.nome=nome;
this.estado=estado;
this.montanteMax=montanteMax;
public String toString() {
return "Aluno nome=" + nome + ", estado=" + estado + ", montanteMax=" montanteMax; } }

对象文件中的arraylist(根据老师的要求),因此当用户创建新的配置文件时,我会写入对象文件,以便稍后可以加载文件中的信息,以便我可以比较以查看用户是否已创建。但我无法存储 ArrayList,因为它说“无法读取文件”。这是写入文件的函数代码:

private void escrever_ficheiro(String nome, String estado, float montanteMax) {
File f = new File("utilizadores_objetos.txt");
// teste
try {
FileOutputStream fos = new FileOutputStream(f,true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Aluno aluno = new Aluno(nome,estado,montanteMax);
listaAlunos.add(aluno);
oos.writeObject(listaAlunos);
oos.close();
} catch (FileNotFoundException ex) {
System.out.println("Erro ao criar ficheiro");
} catch (IOException ex) {
System.out.println("Erro ao escrever para o ficheiro");
}

}

以及加载它的那个:

public static void ler_ficheiro() {
File f = new File("utilizadores_objetos.txt");
if (f.exists() && f.isFile()) {
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String linha;
if ((linha=br.readLine()) != null) {
br.close();
try {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
listaAlunos = (ArrayList<Aluno>) ois.readObject();
ois.close();
}
catch (FileNotFoundException e) {
System.out.println("Não encontrei o ficheiro");
}
}
} catch (FileNotFoundException ex) {
System.out.println("Erro a abrir ficheiro.");
} catch (IOException ex) {
System.out.println("Erro a ler ficheiro.");
} catch (ClassNotFoundException ex) {
System.out.println("Erro a converter objeto.");
}
}
}

我也有这个函数,所以我可以创建 arrayList:

public class AplicacaoViagem{
private List<Aluno> listaAlunos;
public AplicacaoViagem() {
super();
listaAlunos = new ArrayList<>();
}
}

我在 Eclipse 中收到“listaAlunos 无法解析为变量”错误。每段代码都在不同的 .java 文件中,但它仍然不起作用。

最佳答案

不要将整个数组写入文件,而是将每个元素写入文件。您对 toString() 覆盖的想法是正确的。

我将更改toString()如下

@Override
public String toString() {
return String.format("%s:%s:%f", nome, estado, montanteMax);
}

然后您可以写出要归档的项目,如下所示:

public void writeToFile(List<Aluno> objectList) {
String data = objectList
.stream()
.map(obj -> obj.toString())
.collect(Collectors.joining("\n"));

Files.write(Paths.get("utilizadores_objetos.txt"),
data.toByte(StandardCharsets.UTF_8),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
}

然后,如果您想读回文件,您可以执行以下操作:

public List<Aluno> readFile() throws IOException {
List<Aluno> list = Files.readAllLines(Paths.get("utilizadores_objetos.txt"))
.stream()
.filter(s -> !s.trim().isEmpty())
.map(s -> new Aluno(s))
.collect(Collectors.toList());
return list;
}

然后在您的 Aluno 类中添加此构造函数:

public Aluno(String data) {
String items = data.split(":");
nome = items[0];
estado = items[1];
montanteMax = Float.parseFloat(items[2]);
}

确保添加正确的错误处理。

这应该可以让您找到所需的内容,读取和写入文件。

关于java - 无法在目标文件中存储和加载数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53768035/

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