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

Java-从第二行开始读取文本文件,java,csv,io,Java,Csv,Io,我正在尝试用java读取一个txt文件。但是,我只想从第二行开始阅读,因为第一行只是一个标签。这就是一个例子 文本文件: Name,Type,Price Apple,Fruit,3 Orange,Fruit,2 Lettuce,Veggie,1 我该怎么做?我有这个代码,你们可以从第一行读 代码: 请帮助我,提前谢谢。只需添加一个额外的BufferedReader#readLine呼叫 br.readLine(); // consume first line and ignore line =

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

文本文件:

Name,Type,Price
Apple,Fruit,3
Orange,Fruit,2
Lettuce,Veggie,1
我该怎么做?我有这个代码,你们可以从第一行读

代码:


请帮助我,提前谢谢。

只需添加一个额外的
BufferedReader#readLine
呼叫

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

只需阅读并跳过第一行

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

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

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

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

   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"));
   }
CSVParser parser=CSVParser.parse(文件,Charset.forName(“UTF-8”),CSVFormat.RFC4180.withFirstRecordAsHeader().withSkipHeaderRecord());
List records=parser.getRecords();
用于(CSVRecord记录:记录){
System.out.println(record.get(“Name”));
System.out.println(record.get(“Type”));
System.out.println(record.get(“Price”);
}

我提出了一个不同的解决方案:忽略行而不查看它们。。。当然工作;但这种方法在文件内容发生更改时并不十分可靠

如果将文件更改为

header

data

因此,我的建议是这样的——保留您当前的代码,但确保只选择包含有效数据的行;例如,通过返工循环体:

lines = line.split(",");
if (lines.length == 3 && isNumber(lines[2])) ...
其中,isNumber()是一个小辅助函数,用于检查传入字符串是否正确,即数字

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


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

我认为您正在将txt文件转换为CSV解析器

所以我建议你

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

这个答案证明了“不要让它变得比必须的更难”:-@Gikkman但它也是一个很好的例子,说明了不太健壮的代码是如何产生的。@GhostCat你有一个很好的观点。根据项目所需的健壮性和寿命,简单的解决方案并不总是解决方案的正确答案,这是文本文件的要求哈哈
lines = line.split(",");
if (lines.length == 3 && isNumber(lines[2])) ...
br.readLine(); // Header of CSV
line = br.readLine();
while(line != null)
{
 // Your Logic
}