使用 JAVA 从 CSV 文件中读取列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19931929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:38:11  来源:igfitidea点击:

Reading a column from CSV file using JAVA

javacsv

提问by Newbie

Hi I am trying to read a CSV File called test.csvin JAVA . Below is my code :

嗨,我正在尝试读取test.csv在 JAVA 中调用的 CSV 文件。下面是我的代码:

import java.io.BufferedReader;
import java.io.FileReader;

public class InsertValuesIntoTestDb {

    @SuppressWarnings("rawtypes")
    public static void main(String[] args) throws Exception {
                String splitBy = ",";
        BufferedReader br = new BufferedReader(new FileReader("test.csv"));
        String line = br.readLine();
        while(line!=null){
             String[] b = line.split(splitBy);
             System.out.println(b[0]);
        }
        br.close();

  }
}

This is my CSV File (test.csv):

这是我的 CSV 文件 (test.csv):

a,f,w,b,numinst,af,ub
1RW,800,64,22,1,48:2,true
1RW,800,16,39,1,48:2,true
1RW,800,640,330,1,48:2,true
1RW,800,40,124,1,48:2,true
1RW,800,32,104,1,48:2,true
1RW,800,8,104,1,48:2,true
1R1W,800,65536,39,1,96:96,true
1R1W,800,2048,39,1,96:96,true
1R1W,800,8192,39,1,48:48,true

I am trying to print the first column in the csv ,but the output I get is only ain an infinite loop . Can anyone please help me fix this code to print the entire first column. Thanks.

我正在尝试打印 csv 中的第一列,但我得到的输出只是a无限循环。任何人都可以帮我修复此代码以打印整个第一列。谢谢。

采纳答案by Reimeus

Read the input continuously within the loop so that the variable lineis assigned a value other than the initial value

在循环内连续读取输入,以便为变量line分配初始值以外的值

while ((line = br.readLine()) !=null) {
  ...
}

Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writingCSV files

旁白:这个问题已经使用 CSV 库(例如OpenCSV )解决了。以下是读取和写入CSV 文件的示例

回答by Matt Rink

You are not changing the value of line. It should be something like this.

您没有更改 line 的值。它应该是这样的。

import java.io.BufferedReader;
import java.io.FileReader;

public class InsertValuesIntoTestDb {

  @SuppressWarnings("rawtypes")
  public static void main(String[] args) throws Exception {
      String splitBy = ",";
      BufferedReader br = new BufferedReader(new FileReader("test.csv"));
      while((line = br.readLine()) != null){
           String[] b = line.split(splitBy);
           System.out.println(b[0]);
      }
      br.close();

  }
}

readLine returns each line and only returns null when there is nothing left. The above code sets line and then checks if it is null.

readLine 返回每一行,只有在没有任何东西时才返回 null。上面的代码设置 line 然后检查它是否为空。

回答by Paul Vargas

If you are using Java 7+, you may want to use NIO.2, e.g.:

如果您使用的是Java 7+,则可能需要使用NIO.2,例如:

Code:

代码:

public static void main(String[] args) throws Exception {

    File file = new File("test.csv");

    List<String> lines = Files.readAllLines(file.toPath(), 
            StandardCharsets.UTF_8);

    for (String line : lines) {
        String[] array = line.split(",", -1);
        System.out.println(array[0]);
    }

}

Output:

输出:

a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W

回答by Pratiyush Kumar Singh

Splitting by comma doesn't work all the time for instance if you have csv file like

例如,如果您有像

"Name" , "Job" , "Address"
"Pratiyush, Singh" , "Teacher" , "Berlin, Germany"

So, I would recommend using the Apache Commons CSVAPI:

因此,我建议使用Apache Commons CSVAPI:

    Reader in = new FileReader("input1.csv");
    Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
    for (CSVRecord record : records) {
      System.out.println(record.get(0));
    }