import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.ArrayList;
/**
* Write a description of class ReadInCsv here.
*
* @author (Kevin Knapp)
* @version (10-10-2013)
*/
public class ReadInCsv
{
public static void main(String[] args)
{
String csvName = "Countries.csv";
File csvFile = new File(csvName);
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> popList = new ArrayList<>();
ArrayList<String> areaList = new ArrayList<>();
ArrayList<String> gdpList = new ArrayList<>();
ArrayList<String> litRateList = new ArrayList<>();
try
{
Scanner in = new Scanner(csvFile).useDelimiter(",");
while (in.hasNext())
{
String name = in.next();
nameList.add(name);
String pop = in.next();
popList.add(pop);
String area = in.next();
areaList.add(area);
String gdp = in.next();
gdpList.add(gdp);
String litRate = in.next();
litRateList.add(litRate);
}
in.close();
System.out.println(nameList);
System.out.println(popList);
System.out.println(areaList);
System.out.println(gdpList);
System.out.println(litRateList);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
所以我试着从csv文件中读取它并将其通过它应该将每个扫描的实例添加到数组列表中(我将在稍后的时间点从这些列表中引用每个元素),但我的输出显示尽快当它读取并添加它时,它会在读取下一个字符串之前跳到下一行,我需要它直接读取,而不是对角线
我确定我只是遗漏了一些非常简单的东西,我刚开始在一周前开始学习java,感谢您的帮助
答案 0 :(得分:1)
此方法的一个大问题是,除非文件中的每一行以逗号结尾,否则不会分隔换行符。更好的方法是读取每一行,用逗号分割,并一次将值添加到ArrayLists一行:
Scanner in = new Scanner(csvFile);
while (in.hasNextLine()) {
String[] fields = in.nextLine().split(",");
if (fields.length == 5) {
nameList.add(fields[0]);
popList.add(fields[1]);
areaList.add(fields[2]);
gdpList.add(fields[3]);
litRateList.add(fields[4]);
} else {
// Bad line...do what you want to show error here
}
}
更好的方法是使用专用于读取CSV文件的Java库。一个快速的谷歌搜索应该会出现一些好的。