java reading from csv file and storing its information into ArrayList

后端 未结 2 815

I\'m a java newbie and I need a some help

so here is my main method:

RegistrationMethods dmv = new RegistrationMethods();
ArrayList I         


        
相关标签:
2条回答
  • 2020-12-06 19:44

    You could use a method like this and provide the path to the file you wish to read from. This creates a Scanner to read from the file passed in.

    It grabs each line one at a time and adds a new CarOwner(String,String,String,String,String) object to the result array.

    P.S. i have no idea your implementation of CarOwner so i just used all Strings... I'll leave that to you to figure out heh.

    public ArrayList < CarOwner > processTextToCarOwnerList(String filePath) throws IOException {
        ArrayList < CarOwner > result = new ArrayList < CarOwner > ();
        Scanner scan = new Scanner(new File(filePath));
        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            String[] lineArray = line.split(" ");
            result.add(new CarOwner(lineArray[0], lineArray[1], lineArray[2], lineArray[3], lineArray[4]));
            }
            return result;
        }
    
    0 讨论(0)
  • 2020-12-06 19:56

    You could use something like this:

    ArrayList<CarOwner> owners = new ArrayList<CarOwner>();
    
    BufferedReader br = new BufferedReader(new FileReader(new File("path/to/your/file.csv")));
    String line;
    while ((line = br.readLine()) != null) {
    
        String[] entries = line.split(",");
    
        CarOwner owner = new CarOwner(entires[0], entries[1], entries[2], entries[3]);
    
        owners.add(owner);
    }
    

    Do you have a real csv file (all values separated by ,) or are they separated by spaces or something like that? In that case you'd have to replace the , with spaces.

    0 讨论(0)
提交回复
热议问题