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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40134193/
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-11-03 04:57:04  来源:igfitidea点击:

Java - read text file starting from second line

javacsvio

提问by Jason Christopher

I am trying to read a txt file in java. However, I only want to read starting from the second line since the first line is just a label. This is the example

我正在尝试用 Java 读取 txt 文件。但是,我只想从第二行开始阅读,因为第一行只是一个标签。这是例子

Text File:

文本文件:

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

How do I do this? I have this code where you can read from first line.

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

Code:

代码:

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

Please help me, Thank you in advance.

请帮助我,在此先感谢您。

回答by flakes

Just add an extra BufferedReader#readLinecall...

只需添加一个额外的BufferedReader#readLine电话...

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

回答by Arnaud

In case you are interested in using a third party library, here is an example using Apache Commons CSV(it will skip the header, but keep its mapping for retrieval of fields from the record).

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

Modify the charset according to your file's encoding.

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

   CSVParser parser = CSVParser.parse(file, Charset.forName("UTF-8"),CSVFormat.RFC4180.withFirstRecordAsHeader().withSkipHeaderRecord());

   List<CSVRecord> 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"));
   }

回答by Keval Pithva

I think you are converting txt file into CSV Parser

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

So I suggest you..

所以我建议你..

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

回答by Shreyas Sarvothama

Just do the following in while condition:

只需在 while 条件下执行以下操作:

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

回答by ControlAltDel

Just read and skip the first line

只需阅读并跳过第一行

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

回答by GhostCat

I propose a somehow different solution: ignoring lines without having a look into them ... of course works; but that approach is not very robust upon changes to your file content!

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

What happens if you change your files to have

如果您将文件更改为

header

data

or

或者

data
data

So, my suggestion goes like this --- keep your current code, but ensure that you only pick lines with validdata; for example by reworking your loop body:

所以,我的建议是这样的——保留你当前的代码,但确保你只选择带有有效数据的行;例如通过改造你的循环体:

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

where isNumber()is a little helper function that checks if the incoming string is well, a number.

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

In other words: skipping lines intentionally implicitly hard codesknowledge about the file layout into your "parser". That might be OK for simple exercises, but in the real worldsuch things willbreak at some point in the future. And then the fun begins. Because nobodywill remember that the parsing code is written to throw away the first line of the file.

换句话说:有意地跳过行将有关文件布局的知识硬编码到您的“解析器”中。这对于简单的练习来说可能没问题,但在现实世界中,这样的事情在未来的某个时候崩溃。然后乐趣开始了。因为没有人会记得解析代码是为了扔掉文件的第一行而写的。

And as shown, you can easily avoid that kind of problem!

如图所示,您可以轻松避免此类问题!