[英]Creating Strings while Reading a CSV ( Java)
I'am Scanning a CSV File with the following Code: 我正在使用以下代码扫描CSV文件:
public void scanFile() {
boolean isNumber = false;
String test;
try {
sc = new Scanner(Gui.selectedFile);
sc.useDelimiter("[;\"]");
while (sc.hasNext() && isNumber == false) {
test = sc.next();
if(test.equals("{9}")) {
System.out.println("success");
}
System.out.println();;
if (sc.hasNextInt()) {
isNumber = true;
}
} sc.close();
} catch (Exception e) {
System.out.println("error");
}
Now i need a way, to create a String for EACH entry in the CSV. 现在,我需要一种方法来为CSV中的每个条目创建一个字符串。 There are around 60 entry's in my CSV.
我的CSV中大约有60个条目。 I need to use the read data further in the program.
我需要在程序中进一步使用读取的数据。
You can do it the following way with just 3 lines of code: 您只需3行代码即可通过以下方式进行操作:
List<List<String>> data = new ArrayList<List<String>>();
List<String> lines = Files.lines(Paths.get(file)).collect(Collectors.toList());
lines.stream().forEach(s -> data.add(Arrays.asList(s.split(","))));
Here's what it does. 这就是它的作用。 The second line above reads all the lines from the CSV file.
上面的第二行从CSV文件读取所有行。 In the third line, we stream through all the lines (one line at a time) and split the line with a comma as a separator.
在第三行中,我们流经所有行(一次一行),并用逗号分隔行。 This split gives us an array of cells in that line.
这种划分为我们提供了该行中的一组单元格。 We just convert the array to a list and add it to our datastructure
data
which is a list of lists. 我们只是将数组转换为列表,然后将其添加到作为列表列表的
data
结构data
中。
Later, say, if you want to access the value of 7th cell in the 4th row of the CSV, all you have to do is following: 稍后,说一下,如果要访问CSV第四行中的第7个单元格的值,则只需执行以下操作:
String cell = data.get(3).get(6);
public ArrayList<String> scanFile() {
boolean isNumber = false;
String test;
ArrayList<String> output = new ArrayList<String>();
try {
sc = new Scanner(Gui.selectedFile);
sc.useDelimiter("[;\"]");
while (sc.hasNext() && isNumber == false) {
test = sc.next();
output.add( test );
if(test.equals("{9}")) {
System.out.println("success");
}
System.out.println();;
if (sc.hasNextInt()) {
isNumber = true;
}
} sc.close();
} catch (Exception e) {
System.out.println("error");
}
return output;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.