2016-12-21 4 views
0

나는 csv를 반복 중입니다.두 번째 열 (FileReader) 선택

1) 내가 열 이름을 넣어하지 않으

if(tab[1].equals("Col2") 

같은 이름으로 두 번째 열을 선택 해요 : 저는 두 가지 질문이 있습니다. 두 번째 열만 선택하고 싶습니다.

String csvFile = "C:\\test.csv"; 
BufferedReader br = null; 
String line = ""; 
String cvsSplitBy = ";"; 

try{ 
    br = new BufferedReader(new FileReader(csvFile)); 

    while ((line = br.readLine()) != null) { 
     String[] tab=line.split(cvsSplitBy);  

     int tmp; 
     if(tab[1].equals("Col2")){     

      tmp = Integer.parseInt(tab[2]); 

       for(int i=0;i<tmp;i++){ 
        // TO DO 
       } 
     } 
    } 
} 
+1

안녕하세요, 당신은 lib 디렉토리 opencsv 시도 할 수 있습니다. – Cotrariello

+0

1) 이름으로 열을 선택하지 않고, 두 번째 열을'tab [1]'로 선택하고''Col2 ''와 비교합니다. 아니면 내가 그 질문을 오해 했습니까? – njlarsson

+0

@njlarsson - 올바른 – 4est

답변

1

나은 이것을 위해 CSVReader 활용하는, 처리를위한 API를 많이 제공한다 : 첫 번째 행 (헤더)를 이동하는 방법

2)

여기

루핑 CSV의 코드 샘플은 귀하의 csv 파일. 다음은 예외 처리없이 완전한 작업 코드입니다.

String csvFile = "C:\\test.csv"; 
CSVReader reader; 
String[] nextRow; 
char cvsSplitBy = ';'; 

try { 

    //Last argument will determine how many lines to skip. 1 means skip header 
    reader = new CSVReader(new FileReader(csvFile), cvsSplitBy, CSVParser.DEFAULT_QUOTE_CHARACTER, 1); 

    while ((nextRow = reader.readNext()) != null) { 

     if(nextRow.length > 2){ 
      //nextRow[1] will always give second column value 
      int tmp = Integer.parseInt(nextRow[1]); 
      for (int i = 0; i < tmp; i++) { 
       // TO DO 
      } 
     } 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

않았다 br.readLine(); .......... 이제 이름을 사용하지 않는 열을 선택하는 방법? – 4est

+0

'CSVReader' 또는'BufferedReader' 자체를 사용 했습니까? –

+0

나는 CSV .....로 바뀌고 있습니다. 지금 루프를 보면서 어떻게 봐야합니까? while ((line = br.readLine())! = null) – 4est

0

여기 Apache Commons CSV, 그 CSVParser를 사용한 예이다.

첫 번째 줄은 머리글로 간주되어 건너 뜁니다 (withFirstRecordAsHeader()). 각 레코드의 "열"은 해당 인덱스 (get(int))로 액세스 할 수 있습니다. 인덱스는 0부터 시작합니다.

필요에 따라 문자셋 및 CSVFormat을 변경하십시오. 이 여기에 게시 된 모든 다른 솔루션이 실패합니다 반면 행 중 일부는 단지 하나의 열이 빈 경우에도 작동합니다

CsvParserSettings parserSettings = new CsvParserSettings(); //many options here, check the tutorial. 
parserSettings.setHeaderExtractionEnabled(true); //header is extracted and not part of the result 
parserSettings.selectIndexes(1); //select 2nd column (indexes are 0-based) 
CsvParser parser = new CsvParser(parserSettings); 
List<String[]> allRows = parser.parseAll(csvFile); 

참고 :이 케이크 한 조각이된다 univocity-parsers으로

CSVParser parser = null; 

try { 

    parser = CSVParser.parse(new File(csvFile), Charset.forName("UTF-8"), 
      CSVFormat.RFC4180.withFirstRecordAsHeader()); 

    List<CSVRecord> records = parser.getRecords(); 

    for (CSVRecord record : records) { 

     int tmp = Integer.parseInt(record.get(1)); 

     for (int i = 0; i < tmp; i++) { 
      // TO DO 
     } 

    } 

} catch (IOException e) { 

    e.printStackTrace(); 

} finally { 
    try { 
     parser.close(); 
    } catch (IOException e) { 

    } 

} 
0

혼자서 그런 상황을 다루지 않는 한.

이뿐 만 아니라 코드와 복잡성이 줄어들뿐만 아니라 파서는 Commons CSV보다 ~ 4 배 빠르고 OpenCSV보다 3 배 빠릅니다.

면책 조항 : 나는이 라이브러리의 저자 해요, 그것은 오픈 소스와 자유 (아파치 2.0 라이선스)

+0

안녕하세요, csvFile 아래에 넣을 수 있습니다 : String csvFile = "C : \\ test.csv"? – 4est

+0

다음과 같은 작업을 수행 할 필요가 없습니다. File csvFile = new File ("c : /test.csv"); –

관련 문제