BAEL-6790: Write and Read file with HashMap (#15087)
* Add examples for reading and writing a HashMap from a file * Add test for gson
This commit is contained in:
parent
0db917b0ce
commit
c0a9532c64
@ -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)
|
@ -6,6 +6,10 @@
|
||||
<artifactId>core-java-collections-maps-7</artifactId>
|
||||
<name>core-java-collections-maps-7</name>
|
||||
<packaging>jar</packaging>
|
||||
<properties>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<csv.version>1.5</csv.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
@ -13,72 +17,24 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.2.5.RELEASE</spring.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.12.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>1.36</version>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.8.9</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>20230227</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.1</version>
|
||||
<scope>test</scope>
|
||||
<version>${gson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-csv</artifactId>
|
||||
<version>1.5</version>
|
||||
<version>${csv.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@ -92,5 +48,4 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
@ -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<Integer, Student> 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<String, String> 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<String, String> 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<Integer, Student> studentsFromFile;
|
||||
try (FileInputStream fileReader = new FileInputStream(file); ObjectInputStream objectStream = new ObjectInputStream(fileReader)) {
|
||||
studentsFromFile = (HashMap<Integer, Student>) 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<Integer, Student> mapFromFile;
|
||||
try (FileInputStream fileInput = new FileInputStream(file)) {
|
||||
// Create a TypeReference so we can deserialize the parameterized type
|
||||
TypeReference<HashMap<Integer, Student>> mapType = new TypeReference<HashMap<Integer, Student>>() {
|
||||
};
|
||||
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<Integer, Student> studentsFromFile;
|
||||
try (FileReader reader = new FileReader(file)) {
|
||||
Type mapType = new TypeToken<HashMap<Integer, Student>>() {
|
||||
}.getType();
|
||||
studentsFromFile = gson.fromJson(reader, mapType);
|
||||
}
|
||||
assertThat(studentsFromFile).isEqualTo(STUDENT_DATA);
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user