我正在努力学习Java ... 我正面临一个(简单)问题。
==>我有一个csv文件:
This road;123;That place
Another road;456;Another place
==>我有一些java代码:
package tijdelijk;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReadFromCSV {
public static void main(String[] args) {
String CSVadres = "src/tijdelijk/ReadFromCSV.csv";
try (Scanner adresScanner = new Scanner(new File(CSVadres))) {
adresScanner.useDelimiter(";");
while (adresScanner.hasNext()) {
String adresIter = adresScanner.next();
int nummerIter = Integer.parseInt(adresScanner.next());
String plaatsIter = adresScanner.nextLine();
System.out.println("straat\t\t" + adresIter);
System.out.println("huisnummer\t" + nummerIter);
System.out.println("plaats\t\t" + plaatsIter);
System.out.println("\n");
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ReadFromCSV.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
==>我有输出:
run:
straat This road
huisnummer 123
plaats ;That place
straat Another road
huisnummer 456
plaats ;Another place
BUILD SUCCESSFUL (total time: 0 seconds)
==>我有一个问题......
为什么我会在“plaats”字段中获得分号? 我该如何编写代码来修复此问题?
提前感谢您的帮助。 来自荷兰的亲切问候, 皮尔
答案 0 :(得分:0)
Scanner#useDelimiter
方法将正则表达式字符串作为输入。所以你可以通过定义两个分隔符来使用它,如下面的
adresScanner.useDelimiter(";|\n");
第一个是你的内联分隔符,第二个是换行符分隔符。
然后,您不再需要使用nextLine()
,而只需next()
答案 1 :(得分:0)
您可以将整行读取为字符串,然后根据分号拆分该字符串,并将拆分字符串放入数组中,而不是使用扫描程序:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
String CSVadres = "C:/LCC Lev 4/test.csv";
try (Scanner adresScanner = new Scanner(new File(CSVadres))) {
while (adresScanner.hasNext()) {
String fullAddress = adresScanner.nextLine();
String [] addFields = fullAddress.split(";");
String adresIter = addFields[0];
String nummerIter = addFields[1];
String plaatsIter = addFields[2];
System.out.println("straat\t\t" + adresIter);
System.out.println("huisnummer\t" + nummerIter);
System.out.println("plaats\t\t" + plaatsIter);
System.out.println("\n");
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}