1. Overview
2. Write Objects in a File
When dealing with textual files and objects, we should be aware that we cannot easily store the entire object in the text file. To store entire objects, we can use bytes of stream and binary files.
Furthermore, the text files contain only string values. In other words, whatever we store will be stored as a string. Therefore, we’d get the String values back from a file.
Now, we’ll use the PrintWriter class and its println() method to write data in the text file. Using PrintWriter, we can store the String representation of an object. If we pass the entire object as an argument of the println() method, Java will call the toString() method on our object.
class Order { private UUID orderNumber; private double price; public Order(UUID orderNumber, double price) { this.orderNumber = orderNumber; this.price = price; } // getters and setters }
@Override public String toString() { return orderNumber + ";" + price; }
Order order = new Order(UUID.randomUUID(), 50.85);
try (FileWriter fileWriter = new FileWriter(filePath, true); PrintWriter printWriter = new PrintWriter(fileWriter)) { printWriter.println(order); } catch (Exception e) { System.err.println("Error - " + e); }
When we execute the code, the following data will appear in the file:
cab5d1ae-0730-4e19-8c4d-c63fbfec0849;50.85
Each value is separated by the delimiter. Using a specific delimiter can come in handy if we need to read values from the text file.
3. Read Objects from File Using BufferedReader Class
We can read objects from a file using BufferedReader class. Lines in text files are represented as string values. Inside our text file, each line contains data of one object. Moreover, an object’s attributes are separated using “;” as a delimiter.
Now, let’s create an instance of BufferReader class:
BufferedReader br = new BufferedReader(new FileReader(filePath));
Using the while statement we can read each line from the file:
List<Order> orders = new ArrayList<>(); while ((row = br.readLine()) != null) { System.out.println(row); String[] data = row.split(";"); UUID orderNumber = UUID.fromString(data[0]); String price = data[1]; orders.add(new Order(orderNumber, Double.parseDouble(price))); }
The while statement will be executed until lines in the file exist. We can split each line using a delimiter. We can create a new instance of an Order class and add it to the list.