java使用逗号作为分隔符,在txt文件中的三个字符串之间。但文件中的某些行在第二个字符串中有逗号
有一个文件。包含以下内容的txt文件:
Country,Province/State,City
所以我想用“,”作为分隔符。但是,此文件的某些行具有:
Country,"Name1 and Name2, Province of",City
因此,使用逗号作为分隔符不会像上面的示例那样在省名称中使用逗号
这是我的代码:
String path = workingDir + "/src/main_pkg/File.txt";
File file = new File(path);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println(new File("."));
e.printStackTrace();
}
ObservableList<String> listOfProvinces = FXCollections.observableArrayList();
String country;
String state= "";
String lastState = "";
sc.useDelimiter(",");
while (sc.hasNext()) {
country = sc.next();
province = sc.next();
if (country.matches(countryComboBox.getValue())) {
if (!province.matches(lastState)) {
listOfStates.add(state);
lastState = state;
}
}
sc.nextLine();
}
sc.close();
为了澄清,我不能修改txt文件
# 1 楼答案
我找到了解决办法。我必须将分隔符更改为:
我从:https://stackoverflow.com/a/1757146/12179513得到的答案Java: splitting a comma-separated string but ignoring commas in quotes也有效,但它使我的程序运行时间更长