Java – 从第二行开始读取文本文件

我试图在java中读取一个txt文件。 但是,我只想从第二行开始读取,因为第一行只是一个标签。 这是一个例子

文本文件:

Name,Type,Price Apple,Fruit,3 Orange,Fruit,2 Lettuce,Veggie,1 

我该怎么做呢? 我有这个代码,你可以从第一行读取。

码:

 //read the file, line by line from txt File file = new File("train/traindata.txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; line = br.readLine(); while(line != null) { lines = line.split(","); //Do something for line here //Store the data read into a variable line = br.readLine(); } fr.close(); 

请帮帮我,提前谢谢。

只需添加一个额外的BufferedReader#readLine调用…

 br.readLine(); // consume first line and ignore line = br.readLine(); while(line != null) ... 

如果您对使用第三方库感兴趣,以下是使用Apache Commons CSV的示例(它将跳过标题,但保留其映射以从记录中检索字段)。

根据文件的编码修改字符集。

  CSVParser parser = CSVParser.parse(file, Charset.forName("UTF-8"),CSVFormat.RFC4180.withFirstRecordAsHeader().withSkipHeaderRecord()); List records = parser.getRecords(); for (CSVRecord record : records) { System.out.println(record.get("Name")); System.out.println(record.get("Type")); System.out.println(record.get("Price")); } 

我认为您正在将txt文件转换为CSV Parser

所以我建议你..

 br.readLine(); // Header of CSV line = br.readLine(); while(line != null) { // Your Logic } 

只需阅读并跳过第一行

 //read the file, line by line from txt File file = new File("train/traindata.txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; line = br.readLine(); boolean first = true; while(line != null) { if (first) { first = false; } else { lines = line.split(","); //Do something for line here //Store the data read into a variable line = br.readLine(); } } fr.close(); 

在条件下执行以下操作:

 line = br.readLine(); while((line=br.readLine()) != null) { lines = line.split(","); //Do something for line here //Store the data read into a variable line = br.readLine(); } fr.close(); 

我提出了一个不同的解决方案:忽略线条而不去看它们……当然有效; 但是在更改文件内容时,这种方法不是很强大!

如果您更改文件会发生什么

 header data 

要么

 data data 

所以,我的建议是这样的 – 保留你当前的代码,但要确保你只选择有效数据的行; 例如,通过重新处理循环体:

 lines = line.split(","); if (lines.length == 3 && isNumber(lines[2])) ... 

其中isNumber()是一个小辅助函数,用于检查传入的字符串是否正确,是否为数字。

换句话说:跳过行故意隐式地将关于文件布局的知识硬编码到“解析器”中。 对于简单的练习来说这可能是好的,但在现实世界中,这样的事情在未来的某个时刻打破。 然后乐趣就开始了。 因为没有人会记住编写解析代码是为了丢弃文件的第一行。

如图所示,您可以轻松避免这种问题!