How to pass CSV file data to an array in Java?

Asked

Viewed 1,589 times

-2

inserir a descrição da imagem aquiI have a. CSV file with several numbers in two columns (1032,54832). I need to take these numbers and pass them to an array. How do I do this?

I made a code to import the file and I can display the numbers, but when it comes to passing the values to the vector, I’m having problems. Below follows what I did (This code is inside a button that displays the numbers inside the file. CSV):

            String LineFile = new String ();

            File fileCSV = new File(LocalFile.getText());

            try 

            {
                Scanner reader = new Scanner(fileCSV);

                while (reader.hasNext())

                {

                    LineFile = reader.nextLine();


                   String numb[] = LineFile.split(",");
                    System.out.println(LineFile);

                }   



            } 



            catch (FileNotFoundException e)

            {

            }
  • Didn’t you already ask that question? Erased and recreated?

  • Yes. I reworked the question and deleted the previous post.

  • 3

    I recommend that you avoid doing this, as the system computes negatively excluded question for your profile, which may result in prohibitions from creating new posts on the site. ALWAYS choose to edit and improve the same post.

  • 3

    You are getting the array given by split but does nothing with it. Missing add to an array. And if you have some kind of mistake then you need to include the error in the question, so that it is clear what problem you are dealing with

  • I appreciate the warning. Stack Overflow’s system policy is terrible on these issues.

  • 1

    And another, Voce does not explain what problems you are having, your question is not very clear, besides the code nor be reproducible. I suggest you edit and explain better at what point you are having difficulties, because with a piece of code q is not even possible to execute, it is difficult to help without understanding the problem

  • How do I not explain? The problem I’m having is passing the values to an array. If the code wasn’t working, then my question would be about the code not working. And in my eclipse is working normally.

  • 1

    Then provide a code that is a [mcve], so it is possible to test and verify the problem

  • It’s a minimal example. It’s the script that I ran through the CSV file.

  • 1

    It is not a minimal, complete and verifiable example, if I paste it and run, nothing will happen. I recommend that you read the link, it is no use to stay resistant and not provide what is requested, who harms themselves not getting help is even Voce. Who comes in the comments is because want to help you, but if you are not willing to provide as requested, Oce complicates and delays even more a solution.

  • You say in the question that you are having problems. What problem exactly?

  • Stateless Dev I’m having trouble passing the file values to the array (or to the arrayList, in this case).

Show 7 more comments

2 answers

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 method Lines() reads all lines of a file and returns a Stream of String, which is then split and returned as a List of String.

Note: this solution assumes that its method LocalFile.getText() is returning a valid file path.

  • I’ll test it. Thank you. :) A question: I put inside the while?

  • No. All this logic of Scanner is done internally by the method lines(). Just let the Try/catch, adding a catch for IOException also.

  • Hello. I put the script in my eclipse. However the following error appeared: "Multiple markers at this line - Syntax error, Insert "}" to complete Methodbody - Line breakpoint:Methodsordering [line: 139] - actionPerformed(Actionevent) - Syntax error, Insert "}" to complete Classbody - Syntax error, Insert ";" to complete Localvariabledeclarationstatement - The method get(URI) in the type Paths is not applicable for the Arguments (File) - Syntax error, Insert "Finally" to complete Trystatement - Syntax error, Insert "}" to complete Block"

  • Are errors concerning you to have { or } more or less in your code. Review your code and make sure each block is opened and closed correctly.

  • In the "Standardcharsets" part it gives this error along with the line error: "Syntax error, Insert "}" to complete Classbody". I have to create this Classbody?

  • No. As I said, your code is missing keys. Review each { has its respective }.

  • The keys are closed correctly. The problem appears when I enter your script.

  • Colleague, I put the code like this and it worked: "Arraylist<String> Numb = (Arraylist<String>) Files.Lines(Paths.get(Localfile.gettext()) . flatMap(Pattern.Compile(",")::splitAsStream) . Collect(Collectors.toList());" There’s something wrong with the code?

  • It should work the way I posted it, but if it worked for you this way, great.

Show 4 more comments

1

If you need to create a vector with the lines of the files, you need to first get the number of lines of the file. This will force you to read the file 2 times: 1) To get the number of lines; 2) Read the contents of the file. One suggestion I give is to use collections instead of vector, because it will only be necessary an I/O operation. 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 Java 8 Ambdas expressions, you can follow the @Statelessdev solution by changing the split character from ";" to ",".

  • Thank you for calling attention to the ";", Claudivan. I changed in my reply.

  • Right. But this code would only display the file numbers, correct?

  • For his code to work as you need it, you must, outside the while, create a list of String and, within the while, add variables to this list col1 and col2.

  • That’s right @Statelessdev. It would look like this: List<LineFile> lines = new ArrayList<LineFile>();&#xA; while(scanner.hasNext()) {&#xA; String[] line = scanner.nextLine().split(",");&#xA; LineFile lf = new LineFile();&#xA; lf.setCol1(line[0]);&#xA; lf.setCol2(line[1]);&#xA; lines.add(lf);&#xA; }

  • @Claudivanmoreira This part of "Linefile lf = new Linefile();" gives the following error: "Multiple markers at this line - Line breakpoint:Methodsordering [line: 174] - actionPerformed(Actionevent) - Linefile cannot be resolved to a type - Linefile cannot be resolved to a type"

  • @Claudivanmoreira Do you know why this error occurs? In my eclipse it is as if Linefile did not exist. He suggests that it be placed only "Line", or "Line2d".

  • @Gabrielaugusto put the stacktrace of the mistake that gets better the staff help you. At first, it seems to me that the import of your class is not being solved. Remove and add it again. Sometimes the eclipse and keeps throwing some mistakes not very clear.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.