简体   繁体   中英

Java: Reading .csv file with only the first word from each line

I'am trying to read a file which is .csv file into an array with the first index of each line in the file.

What I want to achieve is only the first word of each line, not like the image below:

Bonaqua
California
Gallardo
City
Skyline

投寄箱图片

Below is my read file class:

import java.io.File;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class readfile {

    private Scanner s;

    public void openFile() {
        try {
            s = new Scanner(new File(readpath.a));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "File not found!");
        }
    }

    public void readFile() {

        String read = "";

        while (s.hasNextLine()) {
            read += s.nextLine() + "\n";
        }

        String menu[] = read.split("\n");
        Object[] selectionValues = menu;
        String initialSelection = "";

        Object selection = JOptionPane.showInputDialog(null,
                "Please select the Topic.", "Reseach Forum Menu",
                JOptionPane.QUESTION_MESSAGE, null, selectionValues,
                initialSelection);

        JOptionPane.showMessageDialog(null, "You have choosen "
                        + selection + ".", "Reseach Forum Menu",
                JOptionPane.INFORMATION_MESSAGE);

        if (selection == null) {
            JOptionPane.showMessageDialog(null, "Exiting program...",
                    "Research Forum Menu", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
        }
    }

    public void closeFile() {
        s.close();
    }
}

s.nextLine()更改为s.nextLine().split(",")[0]

Can you tell my why you first concat the string with "\\n"

while (s.hasNextLine()) {
            read += s.nextLine() + "\n";
}

and afterwards you split it?

String menu[] = read.split("\n");

That does not make sense to build a string and then split it the way you built it.

ArrayList<String> firstWords = new ArrayList<String>(); // ArrayList instead of a normal String list because you don't know how long the list will be.

while (s.hasNextLine()) {
    firstWords.add(s.nextLine().split(",")[0]);
}

Now you have all your first words in a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM