How can you store any complex data structure in a file and retrieve the file data as the same data structure into your java program easily?
We are going to use the Jackson APIs to demonstrate the above requirement.
Using the following example, we can store any data structure in a file and load the same data structure into our Java Program using the same file.
Pre-requisites:
- Download Jackson API jars(Jackson Core, Jackson Annotations, Jackson Databind) from https://search.maven.org/
- Once downloaded, add the above mentioned JARs to your classpath.
Step 1: Create sample class (DataStructure) which holds your data structure as a variable.
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class DataStructure {
public ArrayList<LinkedHashMap> data = new ArrayList<LinkedHashMap>();
public DataStructure() {
}
public DataStructure(ArrayList<LinkedHashMap> data) {
this.data = data;
}
}
Step 2: Create a method to store the data structure to a File.
static void storeToFile(ArrayList<LinkedHashMap> data) {
try {
String fileName = "test.txt";
FileWriter fw = new FileWriter(fileName);
DataStructure ds = new DataStructure(data);
ObjectMapper objectMapper = new ObjectMapper();
fw.write(objectMapper.writeValueAsString(ds));
fw.close();
} catch (IOException e) {
System.out.println("storeToFile: " + e.getMessage());
}
}
Step 3 : Read the file into your java program in the same data-structure.
static ArrayList<LinkedHashMap> readFileToDataStructure() {
String fileName = "test.txt";
DataStructure ds = new DataStructure();
File f = new File(fileName);
if (f.exists()) {
try {
String fileDataAsString = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
ObjectMapper objectMapper = new ObjectMapper();
ds = objectMapper.readValue(fileDataAsString, DataStructure.class);
} catch (IOException e) {
System.out.println("readFileToDataStructure: " + e.getMessage());
}
}
return ds.data;
}
You can see that, we are returning the required data structure in the readFileToDataStructure method.
To download these APIs and for more information, visit: http://tutorials.jenkov.com/
Comments
Post a Comment