2013-08-19 3 views
6

안녕하세요 여러분 .CSV 파일을 읽고 XML로 구문 분석 할 파서 코드를 작성하고 있습니다. 이것은 내가 가진 코드이며 파일의 첫 번째 줄을 건너 뛰고 싶을 때만 작동합니다. 그래서는 HashMap을 설정하기로 결정하지만 제대로 작동 않습니다Java에서 CSV 파일을 읽는 중 첫 번째 줄 건너 뛰기

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<Integer,String> lineMap = new HashMap<Integer,String>(); 
int k=2; 
while ((line = br.readLine()) != null) { 
    System.out.println(n + " iteration(s) of 1st While Loop"); 

        lineMap.put(k, line); 

    fw.write("   <ASSET action=\"AddChange\">\n"); 
    fw.write("    <HOSTNAME>\n"); 
    hostName=line.substring(0, line.indexOf(",")); 
    fw.append(hostName); 
    fw.write("</HOSTNAME>\n"); 
    fw.write("    <HOSTID>\n"); 
    hostID=line.substring(line.indexOf(",")+1, nthOccurrence(line, ',', 1)); 
    fw.append(hostID); 
    fw.write("</HOSTID>\n"); 
    fw.write("    <MACMODEL>\n"); 
    machineModel=line.substring(nthOccurrence(line, ',', 1)+1, nthOccurrence(line, ',', 2)); 
    fw.append(machineModel); 
    fw.write("</MACMODEL>\n"); 
    fw.write("    <PROMODEL>\n"); 
    processorModel=line.substring(nthOccurrence(line, ',', 2)+1, nthOccurrence(line, ',', 3)); 
    fw.append(processorModel); 
    fw.write("</PROMODEL>\n"); 
    fw.write("    <CORE>\n"); 
    core=line.substring(nthOccurrence(line, ',', 3)+1, nthOccurrence(line, ',', 4)); 
    fw.append(core); 
    fw.write("</CORE>\n"); 
    fw.write("    <PROC>\n"); 
    proc=line.substring(nthOccurrence(line, ',', 4)+1, nthOccurrence(line, ',', 5)); 
    fw.append(proc); 
    fw.write("</PROC>\n"); 
    fw.write("    <TIER>\n"); 
    tier=line.substring(nthOccurrence(line, ',', 5)+1, nthOccurrence(line, ',', 6)); 
    fw.append(tier); 
    fw.write("</TIER>\n"); 
    fw.write("    <PRODNAME>\n"); 
    productName=line.substring(nthOccurrence(line, ',', 6)+1, nthOccurrence(line, ',', 7)); 
    fw.append(productName); 
    fw.write("</PRODNAME>\n"); 
    fw.write("    <VERSION>\n"); 
    version=line.substring(nthOccurrence(line, ',', 7)+1, nthOccurrence(line, ',', 8)); 
    fw.append(version); 
    fw.write("</VERSION>\n"); 
    fw.write("    <SCRIPTDATA>\n"); 
    scriptData=line.substring(nthOccurrence(line, ',', 8)+1, line.length()); 
    fw.append(scriptData); 
    fw.write("</SCRIPTDATA>\n"); 


    fw.write("   </ASSET>\n"); 
    k++; 
}n++; 

이 코드의 주요 부분의 조각입니다. 어떤 아이디어 또는 해결책 ???

+0

유권자가 아니지만 '작동하는 것처럼 보입니다'라고 분명히 말하십시오. –

+0

미안하지만 오히려 작동하지 않는 것 같습니다. – user2643355

+0

우리는 그것을 알고 있습니다. 그러나 앞으로는 어떻게 작동하지 않는지에 대해 더 많이 알게 될 것입니다. 보다 유용한 정보를 제공할수록 질문에 쉽게 답변 할 수 있습니다. –

답변

20

의를 사용 나머지 파일들로부터. 또한 논리를 단순화 할 수 있으므로 csv 구문 분석에 opencsv을 사용하는 것이 좋습니다.

5

interation 변수를 만들고 0으로 초기화하십시오. 루프에서 while 루프의 맨 처음으로 확인하십시오.

String line; 
int iteration = 0; 
while ((line = br.readLine()) != null) { 
    if(iteration == 0) { 
     iteration++; 
     continue; 
    } 
    ... 
    ... 
} 
+0

처음 두 줄을 건너 뛰려면 어떻게해야합니까? 텍스트가있는 한 행과 다음 행은 빈 행/공백입니까? –

+1

@KalaJ :'if (iteration iteration iteration iteration iteration iteration iteration iteration iteration iteration iteration 2)''''''''if (반복문 == 0 || 반복문 == 1)''을 사용하십시오. 알았다? – user1438038

1

난 당신의 코드에 의해 오히려 혼란 스러워요, 당신은 노선도가 있고 당신은 또한 (즉 무엇이든) FW 있습니다. 어느 쪽을 사용하고 있습니까? 당신은 당신이 첫 번째 줄을 건너 뛸하고 싶은 말은,하지만 당신은하지

if (firstLine == true) { 
    firstLine = false; 
    continue; 
} 
나는 또한 내가 심지어 보라 CSVReader 같은 라이브러리를 사용하여 제안

이 속성 ignoreFirstLine을 가지고

http://opencsv.sourceforge.net/apidocs/au/com/bytecode/opencsv/CSVReader.html

2

왜 돈을 't 당신은 당신이 헤더 해부를 소비 그래서 당신은 당신의 while 루프 전에 headerLine = br.readLine()을 배치하는 것이 좋습니다 루프

for(int i=1; (line = br.readLine()) != null; i++) 
{ 
    //Your code 
} 
0

사용하여 버퍼 판독이 같은 두 번 :

while ((line = br.readLine()) != null) { 
    while ((line = br.readLine()) != null) { 
    //your code      
    } 
} 
-1

첫 행 스킵 (이는 일반적으로 열 헤더 포함) 변수를 가지고 처음에있는 동안 반복이 변수를 증가시키고, 계속;

int lineNumber = 0; 

and then in while loop 

while ((line = br.readLine()) != null) { 
         if(lineNumber == 0) { 
          lineNumber++; 
          continue; 
         } 
         lineNumber++; 

         //do waterver u have to do with the tokens in this line(second line) 

      } 
+1

1 년 전에 동일한 기본 답변이 게시되었습니다. –

3

자바 8 풍미 응답을 추가해야한다고 생각합니다. 대신 성능을 공격하지 않을 것이다 플래그를 추가 카운터를 추가

List<String> xmlLines = new BufferedReader(new FileReader(csvFile)) 
    .lines() 
    .skip(1) //Skips the first n lines, in this case 1  
    .map(s -> { 
     //csv line parsing and xml logic here 
     //... 
     return xmlString; 
    }) 
    .collect(Collectors.toList()); 
0
boolean isRecord = false; 
for (CSVRecord record : records) { 
    if(isRecord){ 
     //process records here. 
    }else{ 
     isRecord = true; 
    } 
} 

.