/
Zakonreal
/
practice05
Обзор
Документация
Войти
/
Zakonreal
/
practice05
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/main/java/org/example/serialization/Main.java
67 строк
2 KB
RodinRoman
init
02 май 2025, 02:50
02 май 2025, 02:50
243e955
Код
Авторство
О чём код?
package org.example.serialization; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; public class Main { public Main() throws JsonProcessingException { } public static void main(String[] args) throws IOException { try (FileOutputStream outputStream = new FileOutputStream("intDigits.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream) ){ objectOutputStream.write(212); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } //----------- try (FileOutputStream outputStream = new FileOutputStream("str.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream) ){ objectOutputStream.writeUTF("hello world"); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } //----------- try (FileOutputStream outputStream = new FileOutputStream("user.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream) ){ objectOutputStream.writeObject(new User("Alex", "Petrov", "qwerty")); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } //----------- try (FileInputStream inputStream = new FileInputStream("user.txt"); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); ){ User user = (User) objectInputStream.readObject(); System.out.println("User: " + user); } catch (Exception e) { throw new RuntimeException(e); } User user = new User("Alex", "Petrov", "qwerty"); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(user); System.out.println(json); FileOutputStream outputStream = new FileOutputStream("user.json"); outputStream.write(json.getBytes()); outputStream.close(); User user1 = mapper.readValue(new FileInputStream("user.json"), User.class); System.out.println("Deserialized: " + user1); } }