2016-08-15 44 views
2

我使用apache commons csv來讀取一個CSV文件,我從google trends下載爲相關查詢區右下方有一個CSV獲取內容。該文件的一小部分:的Java讀取csv文件的多個標頭

Category: All categories 
"bluetooth speakers: (1/1/04 - 8/15/16, Worldwide)" 

TOP 
speaker,100 
bluetooth speaker,100 

RISING 
portable speakers bluetooth,Breakout 
portable speakers,Breakout 

我的代碼從文件中讀取:

private void readCsv(String inputFilePath) { 
    try { 
     Reader in = new FileReader(inputFilePath); 
     Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in); 
     for (CSVRecord record : records) { 
      String topic = record.get(0); 
      if (topic != null && !topic.isEmpty()) { 
       System.out.println(topic); 
      } 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

輸出:

bluetooth speakers: (1/1/04 - 8/15/16, Worldwide) 
TOP 
speaker 
bluetooth speaker 
RISING 
portable speakers bluetooth 
portable speakers 

所需的輸出:

speaker 
bluetooth speaker 
portable speakers bluetooth 
portable speakers 

基礎的從谷歌的數據(沒有標題)和兩個頭TOP瑞星我無法提取所需的值。是否有任何配置過濾我可以申請獲得所需的值?

+1

你有什麼有*** ***多在一個物理文件不同的CSV「文件」。在將它們解析爲CSV之前,必須將它們分開。 –

+0

@JimGarrison有沒有可以做的圖書館? –

回答

0

雖然嚴格不是一個很好的解決方案,但我的情況忽略具有單個元件消除了頭的記錄。我仍然在尋找/處理像配置這樣的解決方案,或者擴展一些類來獲得更清晰的解決方案。

private void readCsv(String inputFilePath) { 
    try { 
     Reader in = new FileReader(inputFilePath); 
//   Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in); 
     Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in); 
     for (CSVRecord record : records) { 
      if (record.size() <= 1){ 
       continue; 
      } 
      String topic = record.get(0); 
      if (topic != null && !topic.isEmpty()) { 
       System.out.println(topic); 
      } 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

的原因,這是不是一個很好的解決方案是,因爲可能有很多其他的CSV文件,其中該解決方案可以證明有毛病。仍然可能對某人有用。

+2

對我來說,它看起來更像是將文件拆分成多個部分,用空行分隔。第一個空白行之前的任何內容都是文件標題。空行之後的第一行是節標題。直到下一個空白行的其餘行是節內容,這就是你所追求的內容。 – Andreas

+0

@Andreas任何可以過濾csv文件的庫。我可以使用字符串操作,但不認爲這是一個好的解決方案。我與CSV工作找不到使用Apache的lib –

+0

疑問,任何圖書館有一個解決一個小白。在CSV解析器解析了語法文本之後,它將幫助您解釋文件的語義。 – Andreas