get list object from txt file
Mon Mar 20 2023 02:33:16 GMT+0000 (Coordinated Universal Time)
public getAll throws Exception { String input = "id:59,title:Spring and summershoes,price:20,quantity:3,total:60,discountPercentage:8.71,discountedPrice:55\n" + "id:88,title:TC Reusable Silicone Magic Washing Gloves,price:29,quantity:2,total:58,discountPercentage:3.19,discountedPrice:56"; // Convert the input string to a byte array byte[] bytes = input.getBytes(); // Create a ByteArrayInputStream from the byte array ByteArrayInputStream bis = new ByteArrayInputStream(bytes); // Create an ObjectInputStream from the ByteArrayInputStream ObjectInputStream ois = new ObjectInputStream(bis); // Read the objects one by one and add them to a list List<Product> products = new ArrayList<>(); while (true) { try { Product product = (Product) ois.readObject(); products.add(product); } catch (EOFException e) { break; // End of file reached } } // Close the streams ois.close(); bis.close(); // Print the list of products for (Product product : products) { System.out.println(product); } } } class Product implements Serializable { private String id; private String title; private double price; private int quantity; private double total; private double discountPercentage; private double discountedPrice; // constructor, getters and setters @Override public String toString() { return "Product{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", price=" + price + ", quantity=" + quantity + ", total=" + total + ", discountPercentage=" + discountPercentage + ", discountedPrice=" + discountedPrice + '}'; } public static void writeProductToFile(Product product, String filePath) throws IOException { // Open the file for appending FileWriter fw = new FileWriter(filePath, true); // Convert the product to a string String productString = String.format("id:%s,title:%s,price:%.2f,quantity:%d,total:%.2f,discountPercentage:%.2f,discountedPrice:%.2f\n", product.getId(), product.getTitle(), product.getPrice(), product.getQuantity(), product.getTotal(), product.getDiscountPercentage(), product.getDiscountedPrice()); // Write the string to the file fw.write(productString); // Close the file fw.close(); } //This method takes a Product object and a file path as input parameters. // It first opens the file for appending using a FileWriter. // It then converts the Product object to a string using the String.format() method. // This method uses placeholders to format the string with the values of the // Product object's properties. Finally, the method writes the string to the // file using the FileWriter.write() method and closes the file using the // FileWriter.close() method. // //Note that in this example, we are assuming that the file already exists // and we are appending to it. If the file does not exist, you will need // to modify the code to create the file first. }
Comments