java - 读取CSV文件时如何分隔新行?
问题描述
我正在尝试读取一个文件,其中每行都有数据成员,用逗号分隔,用于填充对象的数据成员,我尝试使用正则表达式“|” 用于分隔“,”和“\n”的符号以及“\r”用于进入新行。但是,在读取第一行之后,不会立即读取第二行的第一个数据成员,而是预先读取“”字符。我使用了错误的正则表达式符号吗?还是我没有使用正确的方法?我读到有很多方法可以解决这个问题并选择使用扫描仪,因为它似乎是最简单的,使用缓冲区读取器似乎非常令人困惑,因为它似乎返回数组而不是我想要得到的单个字符串和整数。
CSV 文件看起来像这样
stringA,stringB,stringC,1,2,3
stringD,stringE,stringF,4,5,6
stringG,stringH,stringI,7,8,9
我的代码看起来像这样
//In list class
public void load() throws FileNotFoundException
{
Scanner input = new Scanner(new FileReader("a_file.csv"));
object to_add; //To be added to the list
input.useDelimiter(",|\\n|\\r");
while (input.hasNext())
{
String n = input.next(); //After the first loop run, this data gets the value ""
String l = input.next(); //During this second run, this member gets the data that n was supposed to get, "stringD"
String d = input.next(); //This one gets "stringE"
int a = input.nextInt(); //And this one tries to get "stringF", which makes it crash
int c = input.nextInt();
to_add = new object(n, l, d, a, b, c); //Calling copy constructor to populate data members
insert(to_add); //Inserting object to the list
}
input.close();
}
解决方案
使用 Apache Commons CSV。这是用户指南https://commons.apache.org/proper/commons-csv/user-guide.html
推荐阅读
- javascript - 原生js中svg视图框上的element.animate
- go - Go中不一致的附加行为?
- python - 如果变量不是None,是否有一种pythonic方法可以向while语句添加条件
- windows - Windows 上的 GIT 问题(文件名或扩展名太长)
- c# - 基于多列的 DISTINCT
- webrtc - TURN 服务器如何向 NAT 后面的对等方发送数据?
- typescript - 打字稿编译器(tsc)抛出错误,但仅在纱线脚本中使用时,否则工作正常
- vb.net - 如何根据 CheckedListBox 选择进行 SQL 查询
- r - 在R中查找URL末尾的数字范围
- python - Python - 根据输入生成变量列表理解表达式