How to pass CSV file data to an array in Java? [duplicate]

-1

Ihavea.CSVfilewithseveralnumbersintwocolumns(1032,54832).Ineedtogetthesenumbersandpassthemtoavector.HowdoIdothis?

ImadeacodetoimportthefileandIcandisplaythenumbers,butatthetimeofpassingthevaluestothevector,I'mhavingproblems.BelowiswhatIdid(Thiscodeisinsideabuttonthatdisplaysthenumbersinsidethe.CSVfile):

StringLineFile=newString();FilefileCSV=newFile(LocalFile.getText());try{Scannerreader=newScanner(fileCSV);while(reader.hasNext()){LineFile=reader.nextLine();Stringnumb[]=LineFile.split(",");
                    System.out.println(LineFile);

                }   



            } 



            catch (FileNotFoundException e)

            {

            }
    
asked by anonymous 19.11.2018 / 00:33

2 answers

1

If you need to create a vector with the lines of the files, you need to first get the number of lines in the file. This will force you to read the file 2 times: 1) To catch the amount of lines; 2) Read the contents of the file. One suggestion I make is to use collections instead of vector, since only one I / O operation is required. In this case, your code would look like this:

public class CSVReader {
public static void main(String[] args) throws IOException {
    File csvFile = new File(LocalFile.getText());
    Scanner scanner = new Scanner(csvFile);
    while(scanner.hasNext()) {
        String[] line = scanner.nextLine().split(",");
        String col1 = line[0];
        String col2 = line[1];
        System.out.println(col1);
        System.out.println(col2);
     }
   }
}

If you are familiar with the lambdas expressions in Java 8, you can follow the @StatelessDev solution by changing the split character of ";" for ",".

    
19.11.2018 / 14:25
1

I will offer a more functional and cleaner alternative:

List<String> numb = Files.lines(Paths.get(new File(LocalFile.getText())).toURI()), StandardCharsets.UTF_8)
                        .flatMap(Pattern.compile(",")::splitAsStream)
                        .collect(Collectors.toList());

The lines () reads all rows from a file and returns a Stream of String , which is then splited and returned as a List of String .

Note: This solution assumes that your LocalFile.getText() method is returning a valid path from a file.

    
19.11.2018 / 13:57