Skip to content

Instantly share code, notes, and snippets.

@pol4xer
Last active August 29, 2015 14:21
Show Gist options
  • Save pol4xer/1bed56ab0084294f14b2 to your computer and use it in GitHub Desktop.
Save pol4xer/1bed56ab0084294f14b2 to your computer and use it in GitHub Desktop.
Serialization
public class Serialization
{
public static ArrayList<Profile> profiles = new ArrayList<Profile>();
public static void main(String[] args)
{
profiles = (ArrayList<Profile>) deserData("profiles");
System.out.println(profiles.size());
Profile profile = new Profile();
profile.setName(JOptionPane.showInputDialog(null, "Введите имя:"));
profile.setSurname(JOptionPane.showInputDialog(null, "Введите фамилию:"));
profiles.add(profile);
for(Profile p: profiles){
System.out.println(p.getName()+" "+p.getSurname());
}
System.out.println(profiles.size());
serData("profiles", profiles);
}
public static Object deserData(String fileName){
Object retObject = null;//создаем для того,чтобы сюда записать код(битовый), потом его вернуть в головную программу(sout(2)
try {
FileInputStream fileIn = new FileInputStream(fileName + ".ser");//открываем файл для чтения
ObjectInputStream in = new ObjectInputStream(fileIn);//создаем переменную для чтения
retObject = in.readObject();//читаем битовый код и десир-ем в обычный код
fileIn.close();
in.close();
}catch (IOException e) {System.out.println("Error of in/out");System.exit(1);}
catch (ClassNotFoundException e) {System.out.println("Class not found"); System.exit(2);}
return retObject;
}
public static void serData(String fileName, Object obj){
try {
FileOutputStream fileOut = new FileOutputStream(fileName + ".ser");//создает файл куда будем записывать
ObjectOutputStream out = new ObjectOutputStream(fileOut);//создает переменную для записи в файл
out.writeObject(obj);//записываем obj в виде битового кода
fileOut.close();//закрываем файл
out.close();//закрываем переменную
}catch (IOException e) {System.out.println("Error of in/out");System.exit(1);}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment