无法在对象填充中存储和加载数组列表

时间:2018-12-13 18:26:16

标签: java arraylist

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

name

arraylist位于目标文件中(根据老师的要求),因此当用户创建新的配置文件时,我将写入目标文件,以便稍后(例如,将信息加载到文件中)进行比较以查看例如,如果已经创建了用户。 但是我无法存储ArrayList,因为它说“无法读取文件”。 这是写入文件的函数代码:

import cv2
import matplotlib.pyplot as plt
from skimage.feature import hessian_matrix, hessian_matrix_eigvals

src_path = 'Fundus_photograph_of_normal_left_eye.jpg'

def detect_ridges(gray, sigma=1.0):
    H_elems = hessian_matrix(gray, sigma=sigma, order='rc')
    maxima_ridges, minima_ridges = hessian_matrix_eigvals(H_elems)
    return maxima_ridges, minima_ridges

def plot_images(*images):
    images = list(images)
    n = len(images)
    fig, ax = plt.subplots(ncols=n, sharey=True)
    for i, img in enumerate(images):
        ax[i].imshow(img, cmap='gray')
        ax[i].axis('off')
    plt.subplots_adjust(left=0.03, bottom=0.03, right=0.97, top=0.97)
    plt.show()

img = cv2.imread(src_path, 0) # 0 imports a grayscale
if img is None:
    raise(ValueError(f"Image didn\'t load. Check that '{src_path}' exists."))

a, b = detect_ridges(img, sigma=3.0)

plot_images(img, a, b)

和加载它的那个:

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:

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");
    }

}

并且在Eclipse中出现“无法将listaAlunos解析为变量”错误。 每段代码都位于不同的.java文件中,但仍然无法正常工作。

1 个答案:

答案 0 :(得分:0)

不是将整个数组写入文件,而是将每个元素写入文件。您可以使用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]);
}

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

这应该可以为您提供所需的内容,可以读写文件。