java skip line,在Java中读取CSV文件时跳过第一行

该代码段展示了一个从CSV文件读取并转换为XML的解析器。作者希望忽略文件的第一行(即头部),并在过程中使用HashMap。解决方案建议在while循环前先读取并丢弃头部。此外,推荐使用OpenCSV库来简化解析逻辑。
摘要由CSDN通过智能技术生成

Hey guys I am writing a parser code to read a .csv file and parse it to XML. This is the code I have and it works fine except I would like it to skip the first line in the file. So I decided to set up a HashMap but it does seem to work:

for (int i = 0; i < listOfFiles.length; i++) {

File file = listOfFiles[i];

if (file.isFile() && file.getName().endsWith(".csv")){

System.out.println("File Found: " + file.getName());//Prints the name of the csv file found

String filePath = sourcepath + "\\" + file.getName();

BufferedReader br = new BufferedReader(new FileReader(file));

String line;

int n = 1;

Map lineMap = new HashMap();

int k=2;

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

System.out.println(n + " iteration(s) of 1st While Loop");

lineMap.put(k, line);

fw.write(" \n");

fw.write(" \n");

hostName=line.substring(0, line.indexOf(","));

fw.append(hostName);

fw.write("\n");

fw.write(" \n");

hostID=line.substring(line.indexOf(",")+1, nthOccurrence(line, ',', 1));

fw.append(hostID);

fw.write("\n");

fw.write(" \n");

machineModel=line.substring(nthOccurrence(line, ',', 1)+1, nthOccurrence(line, ',', 2));

fw.append(machineModel);

fw.write("\n");

fw.write(" \n");

processorModel=line.substring(nthOccurrence(line, ',', 2)+1, nthOccurrence(line, ',', 3));

fw.append(processorModel);

fw.write("\n");

fw.write(" \n");

core=line.substring(nthOccurrence(line, ',', 3)+1, nthOccurrence(line, ',', 4));

fw.append(core);

fw.write("\n");

fw.write(" \n");

proc=line.substring(nthOccurrence(line, ',', 4)+1, nthOccurrence(line, ',', 5));

fw.append(proc);

fw.write("\n");

fw.write(" \n");

tier=line.substring(nthOccurrence(line, ',', 5)+1, nthOccurrence(line, ',', 6));

fw.append(tier);

fw.write("\n");

fw.write(" \n");

productName=line.substring(nthOccurrence(line, ',', 6)+1, nthOccurrence(line, ',', 7));

fw.append(productName);

fw.write("\n");

fw.write(" \n");

version=line.substring(nthOccurrence(line, ',', 7)+1, nthOccurrence(line, ',', 8));

fw.append(version);

fw.write("\n");

fw.write(" \n");

scriptData=line.substring(nthOccurrence(line, ',', 8)+1, line.length());

fw.append(scriptData);

fw.write("\n");

fw.write(" \n");

k++;

}n++;

This is a snippet of the main part of the code. Any Ideas or Solutions???

解决方案

You might consider placing headerLine = br.readLine() before your while loop so you consume the header separately from the rest of the file. Also you might consider using opencsv for csv parsing as it may simplify your logic.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值