Search code examples
javajava-17

How to parse file to object in java?


I want to read data from file.txt And then parse it to our object.

For example I have the folllowing ferrari.txt and inside I have

Car{mark='ferrari', model='sf90', productionYear=2020, hp=1000}

now I should parse this to the Car Object.

But all over what I could find on google is not looking like what I should use (maybe I search wrong)

Adding the code : Main:

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        Car car1 = new Car("ferrari", "sf90", 2020, 1000);
        Car car2 = new Car("fiat", "panda", 2015, 95);
        Car car3 = new Car("bmw", "m5CS", 2018, 645);
        Car car4 = new Car("audi", "rs7", 2019, 750);
        List<Car> carList = new ArrayList<>(Arrays.asList(car1, car2, car3, car4));
        createCarFile(carList); //method to create the file (not added in the code)
        write(carList); //method to wride the file (not added in the code)

        readFileByMark("ferrari");
}
 public static void readFileByMark(String mark) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(mark + ".txt"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}

In this code I am reading the file name I want to call in the method - Now I assume that insde this code I have to do the "parse" ?


Solution

  • You cannot "parse" that format. You could do that if you serialized the Car Object in a binary file. But since you are using a plain text file, something like this would not be possible. The format is also not a well-known one (such as JSON). If it were one of the well-known formats, you could use one of the many available libraries out there to do it for you. You could try to map the fields, but that is not that straightforward.

    My suggestion is to change the format to JSON. It is human understandable, quick to work with and there is a variety of libraries supporting it.