How do I write an object to a file and read it back?
Java is pretty amazing with lots of API and with Java 8 we are fully enabled with lots more APIs like Lambda, Method reference, Default methods, Better type interface, Repeating annotations, Method parameter reflections and lot more.
Sometime back I’ve written an article on How to Read JSON Object From File in Java. It was simple java read operation. But in this tutorial we are going to save and load
data from file with simple Production Ready Java Utility.
We are not only saving simple object but we will create simple Java POJO of type CrunchifyCompany and going to save and retrieve object using GSON
. You need below dependency in order for below program to run.
Put below dependency to your maven project. If you have Dynamic Web Project and want to convert it into Maven project then follow these steps.
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3</version> </dependency>
Here is a flow:
- Create class
CrunchifyReadWriteUtilityForFile.java
- Create private inner class
CrunchifyCompany
with two fields- private int
employees
; - private String
companyName
;
- private int
- Create object
crunchify
inside main method - Convert object to
Gson
so it will be saved to file - Use method
crunchifyWriteToFile
to save data to file in Java - Use method
crunchifyReadFromFile
to retrieve data from file in Java
Here is a complete example:
package crunchify.com.tutorial; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; /** * @author Crunchify.com * Best and simple Production ready utility to save/load * (read/write) data from/to file */ public class CrunchifyReadWriteUtilityForFile { private static String crunchify_file_location = "/Users/appshah/Documents/crunchify.txt"; private static Gson gson = new Gson(); // CrunchifyComapny Class with two fields // - Employees // - CompanyName private static class CrunchifyCompany { private int employees; private String companyName; public int getEmployees() { return employees; } public void setEmployees(int employees) { this.employees = employees; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } } // Main Method public static void main(String[] args) { CrunchifyCompany crunchify = new CrunchifyCompany(); crunchify.setCompanyName("Crunchify.com"); crunchify.setEmployees(4); // Save data to file crunchifyWriteToFile(gson.toJson(crunchify)); // Retrieve data from file crunchifyReadFromFile(); } // Save to file Utility private static void crunchifyWriteToFile(String myData) { File crunchifyFile = new File(crunchify_file_location); if (!crunchifyFile.exists()) { try { File directory = new File(crunchifyFile.getParent()); if (!directory.exists()) { directory.mkdirs(); } crunchifyFile.createNewFile(); } catch (IOException e) { log("Excepton Occured: " + e.toString()); } } try { // Convenience class for writing character files FileWriter crunchifyWriter; crunchifyWriter = new FileWriter(crunchifyFile.getAbsoluteFile(), true); // Writes text to a character-output stream BufferedWriter bufferWriter = new BufferedWriter(crunchifyWriter); bufferWriter.write(myData.toString()); bufferWriter.close(); log("Company data saved at file location: " + crunchify_file_location + " Data: " + myData + "\n"); } catch (IOException e) { log("Hmm.. Got an error while saving Company data to file " + e.toString()); } } // Read From File Utility public static void crunchifyReadFromFile() { File crunchifyFile = new File(crunchify_file_location); if (!crunchifyFile.exists()) log("File doesn't exist"); InputStreamReader isReader; try { isReader = new InputStreamReader(new FileInputStream(crunchifyFile), "UTF-8"); JsonReader myReader = new JsonReader(isReader); CrunchifyCompany company = gson.fromJson(myReader, CrunchifyCompany.class); log("Company Name: " + company.getCompanyName()); Integer employee = company.getEmployees(); log("# of Employees: " + employee.toString()); } catch (Exception e) { log("error load cache from file " + e.toString()); } log("\nComapny Data loaded successfully from file " + crunchify_file_location); } private static void log(String string) { System.out.println(string); } }
Eclipse Console Output:
Company data saved at file location: /Users/appshah/Documents/crunchify.txt Data: {"employees":4,"companyName":"Crunchify.com"} Company Name: Crunchify.com # of Employees: 4 Comapny Data loaded successfully from file /Users/appshah/Documents/crunchify.txt
Here is a crunchify.txt file content.
As I ran program two times
you see here JSONObject two times as we are appending value to crunchify.txt
file.
The post In Java How to Save and Load Data from a File – Simple Production Ready Utility for File I/O Read-Write Operation appeared first on Crunchify.
Author: App Shah