import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class FileOperations<T> implements Operations<T> {
private ObjectMapper objectMapper;
//this is going to come from the property file.
private String filePath = "C:\\Users\\phyadavi\\workspace\\ConfigurationService\\src\\main\\resources\\seed.txt" ;
private File file;
public FileOperations() {
this.objectMapper = new ObjectMapper();
this.file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.getMessage();
}
}
}
private void saveImpl(Object serializableObject) throws IOException {
String jsonData = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(serializableObject);
BufferedWriter br = new BufferedWriter(new FileWriter(file));
br.write(jsonData);
br.close();
}
@Override
public void save(List<T> serializableObjects) throws IOException {
saveImpl(serializableObjects);
}
@Override
public void save(T serializableObject) throws IOException {
saveImpl(serializableObject);
}
@Override
public List<T> get() throws IOException {
List<T> list = objectMapper.readValue(file, new TypeReference<List<T>>() {
});
return list;
}
}
import java.io.IOException;
import java.util.List;
import com.cisco.daas.configservice.entities.User;
import com.cisco.daas.configservice.utilities.FileOperations;
import com.cisco.daas.configservice.utilities.Operations;
public class Data {
private static final Operations<User> operations = new FileOperations<User>();
private static List<User> users;
public static List<User> getUsers() {
try {
users = operations.get();
} catch (IOException e) {
e.getMessage();
}
return users;
}
}
The above code reads json data from a text file using the Jacksons ObjectMapper API.
The public List<T> get()
method reads the data from the files and converts the data into a list of objects of type T.
The public void save(T serializableObject)
and public void save(List<T> serializableObjects)
both saves the json data to the file.
The Data
creates a static list objects which is meant for performing operations in-memory.
Now, I would like someone to review the exception handling in the code. I need some idea on how to handle exceptions like NullPointer and FileNotFound exceptions in the above code.