请帮我用 Java 读取 CSV 文件的第一列。这是我的代码:
public void fileload(String filename)throws IOException
{ int i=0;
//Sorter S= new Sorter();
File file=new File(filename); //Read File
Scanner inputfile = new Scanner(file);
while(inputfile.hasNext()) //Reading file content
{
orgarr[i]= inputfile.nextLine();
System.out.println(orgarr[i]);
i++;
}
最佳答案
您可以使用commons-csv这将负责读取格式,例如假设 CSVFormat.DEFAULT
带有可选的带引号的文本列和逗号作为分隔符:
try (FileReader reader = new FileReader("your/path/to/file.csv")) {
CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT);
parser.getRecords().stream()
.map(r -> r.get(0))
.forEach(System.out::println);
}
最佳解决方案取决于您的文件格式和大小。上面可能不适合巨大的 CSV 文件,因为它使用 getRecords()
将所有记录加载到内存中。
关于java - 如何读取 CSV 文件的第一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52914688/