[英]CsvMapReader doesn't appear to parse my file
我有一個非常簡單的tsv文件,其條目如下:
614 2006-07-13 15:30:05 2009-11-20 23:56:21 510 350 3265 10 34
1038 2006-07-15 16:12:15 2009-11-16 05:12:11 304 443 4405 7 156
1437 2006-07-16 12:29:24 2009-11-16 16:25:12 45 73 725 6 37
2615 2006-07-19 23:23:55 2009-11-27 18:34:36 211 230 211 7 0
3148 2006-07-26 14:17:22 2009-11-20 17:35:18 7346 7244 11438 8 97
5593 2006-09-08 10:58:49 2009-11-24 06:08:27 898 1024 2897 8 56
它沒有標題,而且我是從另一個來源獲取的,所以我無法控制它的編寫方式。 我想閱讀第一列,對其進行處理,而忽略其余內容。
我的代碼是:
List<Long> userIds = new ArrayList<Long>();
ICsvMapReader mapReader = null;
try {
mapReader = new CsvMapReader(new FileReader(inFile), CsvPreference.TAB_PREFERENCE);
// only map the first column - setting header elements to null means those columns are ignored
final String[] header = new String[] { "userid", null, null, null, null, null, null };
final CellProcessor[] processors = new CellProcessor[] {null,
null,
null,
null,
null,
null,
null };
Map<String, Object> userMap;
while( (userMap = mapReader.read(header, processors)) != null ) {
Long userId = Long.parseLong(userMap.get("userid").toString());
userIds.add(userId);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
IOUtils.closeQuietly(mapReader);
}
我沒有例外,但是mapReader.read()行始終返回null。 我嘗試在處理器的第一個位置使用new ParseLong()代替null,但這沒有任何效果。 我感覺好像缺少了一些基本的東西。
您的代碼對我來說很好用,盡管我必須在標頭和處理器中添加一個額外的null
元素,因為數據中實際上有8列。 否則,超級CSV會引發異常:
org.supercsv.exception.SuperCsvException: The number of columns
to be processed (8) must match the number of CellProcessors (7):
check that the number of CellProcessors you have defined matches
the expected number of columns being read/written
context={lineNo=1, rowNo=1, columnNo=1, rowSource=
[614, 2006-07-13 15:30:05, 2009-11-20 23:56:21, 510, 350, 3265, 10, 34]}
我會檢查您是否正在讀取正確的文件-聽起來您正在讀取一個空文件...
使用uniVocity-parsers解析您的TSV文件:
TsvParserSettings parserSettings = new TsvParserSettings();
parserSettings.selectIndexes(0); //selects the first column only
TsvParser parser = new TsvParser(parserSettings);
//the rows will contain a String array of length 1, with the values of the first column only.
List<String[]> parsedRows = parser.readAll(new FileReader(yourFile));
另外,請勿使用CSV解析器來解析TSV文件。 解析算法並不等效(即使最初看起來也是如此)。
披露:我是這個圖書館的作者。 它是開源且免費的(Apache V2.0許可證)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.