From c0a9532c647bfee5f6a68d6e4550636940cbd4de Mon Sep 17 00:00:00 2001 From: Lucian Snare Date: Sun, 12 Nov 2023 10:59:00 -0500 Subject: [PATCH] BAEL-6790: Write and Read file with HashMap (#15087) * Add examples for reading and writing a HashMap from a file * Add test for gson --- .../core-java-collections-maps-7/README.md | 4 +- .../core-java-collections-maps-7/pom.xml | 65 ++------- .../map/readandwritefile/Student.java | 51 +++++++ .../ReadAndWriteFileWithHashMapUnitTest.java | 135 ++++++++++++++++++ 4 files changed, 199 insertions(+), 56 deletions(-) create mode 100644 core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/readandwritefile/Student.java create mode 100644 core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/readandwritefile/ReadAndWriteFileWithHashMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index 2e1531050e..a62bdda7af 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -1,5 +1,7 @@ -## Relevant Articles +## Relevant Articles: - [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent) +- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/how-to-write-and-read-a-file-with-a-java-hashmap/) - [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv) - [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair) - [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6) \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-7/pom.xml b/core-java-modules/core-java-collections-maps-7/pom.xml index cefee201cc..a7acded9cf 100644 --- a/core-java-modules/core-java-collections-maps-7/pom.xml +++ b/core-java-modules/core-java-collections-maps-7/pom.xml @@ -1,11 +1,15 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-collections-maps-7 core-java-collections-maps-7 jar + + 2.10.1 + 1.5 + core-java-modules @@ -13,72 +17,24 @@ 0.0.1-SNAPSHOT - - 5.2.5.RELEASE - com.fasterxml.jackson.core jackson-databind - 2.12.4 - - - org.openjdk.jmh - jmh-core - 1.36 + ${jackson.version} com.google.code.gson gson - 2.8.9 - - - org.json - json - 20230227 - - - junit - junit - 4.13.1 - test - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - junit - junit - 4.13.1 - test - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - junit - junit - 4.13.1 - test + ${gson.version} org.apache.commons commons-csv - 1.5 + ${csv.version} + @@ -92,5 +48,4 @@ - diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/readandwritefile/Student.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/readandwritefile/Student.java new file mode 100644 index 0000000000..b981de6300 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/readandwritefile/Student.java @@ -0,0 +1,51 @@ +package com.baeldung.map.readandwritefile; + +import java.io.Serializable; +import java.util.Objects; + +public class Student implements Serializable { + private static final long serialVersionUID = 1L; + private String firstName; + private String lastName; + + /** Default constructor for JSON serialization */ + public Student() { + + } + + public Student(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Student student = (Student) o; + return Objects.equals(firstName, student.firstName) && Objects.equals(lastName, student.lastName); + } + + @Override + public int hashCode() { + return super.hashCode(); + } +} diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/readandwritefile/ReadAndWriteFileWithHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/readandwritefile/ReadAndWriteFileWithHashMapUnitTest.java new file mode 100644 index 0000000000..56867d3885 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/readandwritefile/ReadAndWriteFileWithHashMapUnitTest.java @@ -0,0 +1,135 @@ +package com.baeldung.map.readandwritefile; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import org.junit.After; +import org.junit.Test; +import org.junit.Before; + +public class ReadAndWriteFileWithHashMapUnitTest { + + private static final Map STUDENT_DATA = new HashMap<>(); + + static { + STUDENT_DATA.put(1234, new Student("Henry", "Winter")); + STUDENT_DATA.put(5678, new Student("Richard", "Papen")); + } + + private File file; + + @Before + public void createFile() throws IOException { + file = File.createTempFile("student", ".data"); + } + + @After + public void deleteFile() { + file.delete(); + } + + @Test + public void givenHashMap_whenWrittenAsPropertiesFile_thenReloadedMapIsIdentical() throws IOException { + // Given a map containing student data + Map studentData = new HashMap<>(); + studentData.put("student.firstName", "Henry"); + studentData.put("student.lastName", "Winter"); + + // When converting to a Properties object and writing to a file + Properties props = new Properties(); + props.putAll(studentData); + try (OutputStream output = Files.newOutputStream(file.toPath())) { + props.store(output, null); + } + + // Then the map resulting from loading the Properties file is identical + Properties propsFromFile = new Properties(); + try (InputStream input = Files.newInputStream(file.toPath())) { + propsFromFile.load(input); + } + + Map studentDataFromProps = propsFromFile.stringPropertyNames() + .stream() + .collect(Collectors.toMap(key -> key, props::getProperty)); + assertThat(studentDataFromProps).isEqualTo(studentData); + } + + @Test + public void givenHashMap_whenSerializedToFile_thenDeserializedMapIsIdentical() throws IOException, ClassNotFoundException { + // Given a map containing student data (STUDENT_DATA) + + // When serializing the map to a file + try (FileOutputStream fileOutput = new FileOutputStream(file); ObjectOutputStream objectStream = new ObjectOutputStream(fileOutput)) { + objectStream.writeObject(STUDENT_DATA); + } + + // Then read the file back into a map and check the contents + Map studentsFromFile; + try (FileInputStream fileReader = new FileInputStream(file); ObjectInputStream objectStream = new ObjectInputStream(fileReader)) { + studentsFromFile = (HashMap) objectStream.readObject(); + } + assertThat(studentsFromFile).isEqualTo(STUDENT_DATA); + } + + @Test + public void givenHashMap_whenSerializedToFileWithJackson_thenDeserializedMapIsIdentical() throws IOException { + // Given a map containing student data (STUDENT_DATA) + + // When converting to JSON with Jackson and writing to a file + ObjectMapper mapper = new ObjectMapper(); + try (FileOutputStream fileOutput = new FileOutputStream(file)) { + mapper.writeValue(fileOutput, STUDENT_DATA); + } + + // Then deserialize the file back into a map and check that it's identical + Map mapFromFile; + try (FileInputStream fileInput = new FileInputStream(file)) { + // Create a TypeReference so we can deserialize the parameterized type + TypeReference> mapType = new TypeReference>() { + }; + mapFromFile = mapper.readValue(fileInput, mapType); + } + assertThat(mapFromFile).isEqualTo(STUDENT_DATA); + } + + @Test + public void givenHashMap_whenSerializedToFileWithGson_thenDeserializedMapIsIdentical() throws IOException { + // Given a map containing student data (STUDENT_DATA) + + // When converting to JSON using Gson and writing to a file + Gson gson = new Gson(); + try (FileWriter writer = new FileWriter(file)) { + gson.toJson(STUDENT_DATA, writer); + } + + // Then deserialize the file back into a map and check that it's identical + Map studentsFromFile; + try (FileReader reader = new FileReader(file)) { + Type mapType = new TypeToken>() { + }.getType(); + studentsFromFile = gson.fromJson(reader, mapType); + } + assertThat(studentsFromFile).isEqualTo(STUDENT_DATA); + } +}