使用JAVA从CSV文件中读取列 [英] Reading a column from CSV file using JAVA

查看:3088
本文介绍了使用JAVA从CSV文件中读取列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在尝试在JAVA中读取名为 test.csv 的CSV文件。
以下是我的代码:

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

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();

  }
}

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

This is my CSV File (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

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

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

推荐答案

在循环中连续读取输入,以便变量被分配了一个非初始值的值

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

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

除此之外:此问题已经解决使用CSV库,例如 OpenCSV 。以下是读取和写入 CSV文件的示例

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

这篇关于使用JAVA从CSV文件中读取列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆