java.lang.ClassCastException: java.lang.String не может быть приведен к src.Profesor - Ошибка при попытке прочитать файл - PullRequest
0 голосов
/ 01 мая 2019

Приложение при выполнении создает объект путем ввода данных с клавиатуры и добавляет их в список ArrayList.Я получаю его, чтобы ввести этот объект в файл, но затем, когда я снова запускаю приложение, оно не возвращает содержимое файла консолью.Он бросает мне ошибку в актерском составе


public static ArrayList<Profesor> obtenerArrayListDeArchivo(File profesores2) throws IOException {
        // para ver el contenido del fichero
        String ruta = System.getProperty("user.dir");
        ruta += "\\";// le añadimos el caracter \
        ArrayList<Profesor> lista = new ArrayList<Profesor>();

        FileInputStream fis = new FileInputStream(profesores2);
        ObjectInputStream entrada = new ObjectInputStream(fis);
        try {
            while (true) {
                lista.add((Profesor) entrada.readObject());
            }
        } catch (EOFException ex) { //Con esto detectamos que estamos al final
            entrada.close();
        } catch (ClassNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
        return lista;
    }

Main.java Класс:

public static void main(String[] args) throws Exception {
        final Scanner sc = new Scanner(System.in);
        // leemos el directorio del programa, vamos uno atras y colgamos el fichero
        String ruta = System.getProperty("user.dir");
        // se queda con el path actual y le quitamos el último \directorio
        // ruta = ruta.substring(0, ruta.lastIndexOf("\\"));
        ruta += "\\";// le añadimos el caracter \

        // creamos y abrimos un fichero de texto globales1.txt para grabar el curso y el importe de hora extra
        File globales = new File(ruta + "globales1.txt");
        File profesores2 = new File(ruta + "profesores2.dat");


        ArrayList<Profesor> lista = new ArrayList<Profesor>();

        if (!globales.exists()) { 
            PrintWriter n = new PrintWriter(globales);
            double importe = 0;
            // asignar el atributo estatico curso
            String curso;
            System.out.print("Curso: ");
            curso = sc.nextLine();
            Profesor.setCurso(curso);
            System.out.print("Introduce el importe a pagar por cada hora extra: ");
            double pagoPorHoraExtra;
            importe = sc.nextDouble();
            Profesor.setPagoPorHoraExtra(importe);
            System.out.println();
            globales.createNewFile();
            n.println(curso + "#" + importe);
            n.close();
        } else {

            {
            try {
                lista=Funciones.obtenerArrayListDeArchivo(profesores2);
            } catch (IOException ex)
            {
                System.out.println(ex.getMessage());
            }
            Iterator it3 = lista.iterator();
            while(it3.hasNext())
            {
                System.out.println(it3.next());
            }

        }
...