[英]Java: Reading .csv file with only the first word from each line
我正在嘗試將文件.csv讀入數組,並在文件中每行的第一個索引。
我要實現的只是每行的第一個單詞,而不像下面的圖像:
Bonaqua
California
Gallardo
City
Skyline
以下是我的讀取文件類:
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]
你能告訴我為什么你先用“ \\ n”連接字符串嗎?
while (s.hasNextLine()) {
read += s.nextLine() + "\n";
}
然后拆分?
String menu[] = read.split("\n");
構建字符串然后按照構建方式拆分字符串沒有意義。
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]);
}
現在,您將所有的第一句話都放在列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.