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



我正在尝试存储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]);
}

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

这应该能让你找到你想要的东西,读写到文件中。

最新更新