Я учусь сериализации на Java
Моя проблема в том, что код работает, но я получаю предупреждения, думаю, я его привожу именно так.
Боюсь, что по мере продвижения у меня возникнут проблемы.
Не отмечено предупреждение о приведении из Object в ArrayList.
< /blockquote>
Я пытаюсь создать учетную запись для моего простого проекта.
public class BankAccount implements Serializable {
public String username;
public String password;
public BankAccount() {
super();
// TODO Auto-generated constructor stub
}
public BankAccount(String username, String password) {
super();
this.username = username;
this.password = password;
}
}
Сериализация
BankAccount acc1 = new BankAccount("myuser", "mypass");
BankAccount acc2 = new BankAccount("abcd" , "1234");
BankAccount acc3 = new BankAccount("useracbc" , "pw1234");
ArrayList accounts = new ArrayList();
accounts.add(acc1);
accounts.add(acc2);
accounts.add(acc3);
try {
FileOutputStream fileOut = new FileOutputStream("account.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
out.close();
System.out.println("Account successfully serialized");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Десериализация
ArrayList myList = null;
try {
FileInputStream fileIn = new FileInputStream("account.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
myList = (ArrayList) in.readObject();
fileIn.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(BankAccount list: myList) {
System.out.println(list.username);
System.out.println(list.password);
}
Я попробовал это из Howtodoinjava, но при кастинге все равно получаю то же предупреждение.
ArrayList employeesList = null;
try (FileInputStream fis = new FileInputStream("employeeData");
ObjectInputStream ois = new ObjectInputStream(fis);) {
employeesList = (ArrayList) ois.readObject();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
}
//Verify list data
for (Employee employee : employeesList) {
System.out.println(employee);
}
Подробнее здесь: https://stackoverflow.com/questions/782 ... om-objects
Как правильно сериализовать/десериализовать ArrayList с помощью пользовательских объектов? ⇐ JAVA
Программисты JAVA общаются здесь
1711424320
Гость
Я учусь сериализации на Java
Моя проблема в том, что код работает, но я получаю предупреждения, думаю, я его привожу именно так.
Боюсь, что по мере продвижения у меня возникнут проблемы.
Не отмечено предупреждение о приведении из Object в ArrayList.
< /blockquote>
Я пытаюсь создать учетную запись для моего простого проекта.
public class BankAccount implements Serializable {
public String username;
public String password;
public BankAccount() {
super();
// TODO Auto-generated constructor stub
}
public BankAccount(String username, String password) {
super();
this.username = username;
this.password = password;
}
}
Сериализация
BankAccount acc1 = new BankAccount("myuser", "mypass");
BankAccount acc2 = new BankAccount("abcd" , "1234");
BankAccount acc3 = new BankAccount("useracbc" , "pw1234");
ArrayList accounts = new ArrayList();
accounts.add(acc1);
accounts.add(acc2);
accounts.add(acc3);
try {
FileOutputStream fileOut = new FileOutputStream("account.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(accounts);
out.close();
System.out.println("Account successfully serialized");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Десериализация
ArrayList myList = null;
try {
FileInputStream fileIn = new FileInputStream("account.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
myList = (ArrayList) in.readObject();
fileIn.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(BankAccount list: myList) {
System.out.println(list.username);
System.out.println(list.password);
}
Я попробовал это из Howtodoinjava, но при кастинге все равно получаю то же предупреждение.
ArrayList employeesList = null;
try (FileInputStream fis = new FileInputStream("employeeData");
ObjectInputStream ois = new ObjectInputStream(fis);) {
employeesList = (ArrayList) ois.readObject();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
}
//Verify list data
for (Employee employee : employeesList) {
System.out.println(employee);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78213265/how-to-properly-serialize-deserialize-an-arraylist-with-custom-objects[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия