Java InputStream с различными объектными классами - PullRequest
0 голосов
/ 03 июня 2018

мой код должен прочитать два разных типа объектов (Bestellung, AKunde) через ObjectOutputStream и сохранить его в CSV-файле, который работает.Но когда я пытаюсь прочитать их из файла, это не работает.Вот код:

OutputStream:

LinkedList<Bestellung> bestellListe = verwaltungBestell.getBestellListe();
        try {
            fileOutputStream = new FileOutputStream(file);
            outputStream = new ObjectOutputStream(fileOutputStream);

            for (AKunde kunde : kundenliste) {
                outputStream.writeObject(kunde);
            }
            for (Bestellung bestellung : bestellListe) {
                outputStream.writeObject(bestellung);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

InputStream:

ArrayList<AKunde> kundenImport = new ArrayList<AKunde>();
ArrayList<Bestellung> bestellungenImport = new ArrayList<Bestellung>();
    boolean cont = true;
    try {

ObjectInputStream objectStream = new ObjectInputStream(new FileInputStream(directorie));         
        while (cont) {
            AKunde kunde = null;
            try {
                kunde = (AKunde) objectStream.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();

            }
            if (kunde != null) {
                kundenImport.add(kunde);
            } else {
                cont = false;
            }
        }
        while (cont) {
            Bestellung bestellung = null;
            try {
                bestellung = (Bestellung) objectStream.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();

            }
            if (bestellung != null) {
                bestellungenImport.add(bestellung);
            } else {
                cont = false;
            }
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block

    }

Но он не будет читать "Bestellungen" и не сохранит их в"bestellungenImport".У кого-нибудь есть решение ???

Ответы [ 3 ]

0 голосов
/ 03 июня 2018

Ваш код никогда не достигает части читателя Bestellung.

У вас ложное предположение, что kunde =(AKunde)objectStream.readObject(); возвращает ноль.

Вместо этого выдается исключение.

Один способ, который вы можете сделать, это привести его как @ luk2302.

Другой способ - добавить число объектов при записи потока объекта:

outputStream.writeInt(kundenliste.size());
for (AKunde kunde : kundenliste) {
    outputStream.writeObject(kunde);
}

outputStream.writeInt(bestellListe.size());
for (Bestellung bestellung : bestellListe) {
    outputStream.writeObject(bestellung);
}

Затем замените цикл while(cont) на forкаждый цикл:

int kundeCount = objectStream.readInt();
for (int i = 0; i < kundeCount; i++) {
   // Read and import kunde
}
0 голосов
/ 03 июня 2018

Я бы предложил, чтобы вы сначала изменили способ записи объектов на ObjectOutputStream:

Напрямую пишите объекты kundenListe и bestellListe, так что вам не о чем беспокоитьсяо типах или количестве элементов при повторном чтении объектов.Тогда ваш поток объектов всегда содержит два объекта, два списка.

// use try-with-resources if you're on Java 7 or newer
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file))) {
    // write the complete list of objects
    outputStream.writeObject(kundenliste);
    outputStream.writeObject(bestellListe);
} catch (IOException e) {
    e.printStackTrace(); //TODO proper exception handling
}

Тогда вы можете прочитать это так:

ArrayList<AKunde> kundenImport = new ArrayList<>();
ArrayList<Bestellung> bestellungenImport = new ArrayList<>();

//again try-with-resources
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file))) {
    kundenImport.addAll((List) inputStream.readObject());
    bestellungenImport.addAll((List) inputStream.readObject());
} catch (IOException | ClassNotFoundException  e) { //multi-catch, if Java 7 or newer
    e.printStackTrace(); //TODO proper exception handling
}

Далее читается:

0 голосов
/ 03 июня 2018

Вам нужно изменить логику для чтения объектов.Есть две основные проблемы:

  • вы никогда не сбрасываете cont, поэтому второй цикл while никогда не будет ничего делать
  • , даже если вы сделали это, вы всегда пропустите первый Bestellung так как он уже был прочитан, когда достигнут второй цикл

Я бы предложил что-то вроде:

Object object = objectStream.readObject();
if (object instanceof AKunde) {
    kundenImport.add((AKunde) object);    
} else if (object instanceof Bestellung) {
    bestellungenImport.add((Bestellung) object);
} else {
    // something else was read
}

Вам просто нужно перебрать этот код и добавитьправильная обработка ошибок, где это необходимо.

...