BAEL-7131 version 4 - code review comments.

This commit is contained in:
adalagandev 2024-02-11 19:48:18 +01:00
parent 94fceedf7c
commit 17172ba21a
1 changed files with 31 additions and 0 deletions

View File

@ -1,14 +1,21 @@
package com.baeldung.inputstream;
import static org.junit.jupiter.api.io.CleanupMode.ALWAYS;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
@ -64,4 +71,28 @@ public class InputStreamTest {
}
return sb.toString();
}
@Test
public void givenKeyValuePairs_whenWrittenInATextFile_thenSuccessWhenParsedWithObjectInputStream(
@TempDir(cleanup = ALWAYS) Path tempDir) throws IOException, ClassNotFoundException {
Path sampleOut = tempDir.resolve("sample-out.txt");
File fileText = sampleOut.toFile();
//Serialize a Hashmap then write it into a file.
Map<String, String> kv = new HashMap<>();
try (FileOutputStream fileOutStream = new FileOutputStream(fileText)) {
try (ObjectOutputStream objectOutStream = new ObjectOutputStream(fileOutStream)) {
kv.put("baseURL", "baeldung.com");
kv.put("apiKey", "this_is_a_test_key");
objectOutStream.writeObject(kv);
}
}
//Deserialize the contents of a file then transform it back into a Hashmap
try (FileInputStream fileStream = new FileInputStream(fileText)) {
try (ObjectInputStream input = new ObjectInputStream(fileStream)) {
HashMap<String, String> inputKv = (HashMap<String, String>) input.readObject();
Assert.assertEquals(kv.get("baseURL"), inputKv.get("baseURL"));
Assert.assertEquals(kv.get("apiKey"), inputKv.get("apiKey"));
}
}
}
}