1
通常CSV文件使用製表符,如何能單義性解析器被配置成使得以下可以使用製表符?:CSV文件通常使用製表符分隔符,Univocity解析器.csv解析器如何配置爲允許製表符分隔符?
CsvParserSettings parserSettings = new CsvParserSettings();
當解析的.csv由製表符分隔的文件是必需的,儘管單義性解析器具有TSVreader具有多個設置實例會產生編碼障礙。
代碼和堆棧跟蹤如下。
任何幫助將不勝感激。
import com.univocity.parsers.csv.CsvParserSettings;
import com.univocity.parsers.common.processor.*;
import com.univocity.parsers.csv.*;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.IllegalStateException;
import java.lang.String;
import java.util.List;
public class UnivocityParsers {
public Reader getReader(String relativePath) {
try {
return new InputStreamReader(this.getClass().getResourceAsStream(relativePath), "Windows-1252");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Unable to read input", e);
}
}
public void columnSelection() {
RowListProcessor rowProcessor = new RowListProcessor();
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setLineSeparatorDetectionEnabled(true);
parserSettings.setSkipEmptyLines(true);
parserSettings.getFormat().setDelimiter('\t');
// Here we select only the columns "Price", "Year" and "Make".
// The parser just skips the other fields
parserSettings.selectFields("AUTHOR", "ISBN");
CsvParser parser = new CsvParser(parserSettings);
parser.parse(getReader("list4.csv"));
List<String[]> rows = rowProcessor.getRows();
String[] strings = rows.get(0);
System.out.print(strings[0]);
}
public static void main(String arg[]) {
UnivocityParsers univocityParsers = new UnivocityParsers();
univocityParsers.columnSelection();
}
}
堆棧跟蹤:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
Caused by: java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:97)
at parse.Controller.getReader(Controller.java:34)
at parse.Controller.columnSelection(Controller.java:107)
... 56 more
下面是該文件被解析:
"REVIEW_DATE" "AUTHOR" "ISBN" "DISCOUNTED_PRICE"
"1985/01/21" "Douglas Adams" 345391802 5.95
"1990/01/12" "Douglas Hofstadter" 465026567 9.95
"1998/07/15" "Timothy ""The Parser"" Campbell" 968411304 18.99
"1999/12/03" "Richard Friedman" 60630353 5.95
"2001/09/19" "Karen Armstrong" 345384563 9.95
"2002/06/23" "David Jones" 198504691 9.95
"2002/06/23" "Julian Jaynes" 618057072 12.5
"2003/09/30" "Scott Adams" 740721909 4.95
"2004/10/04" "Benjamin Radcliff" 804818088 4.95
"2004/10/04" "Randel Helms" 879755725 4.5
您是否可以將分隔符設置爲原始十六進制值0x09 ? –
嘗試使用以下命令將分隔符設置爲tab:'parserSettings.getFormat()。setDelimiter((char)0x09);'發生錯誤:'線程中的異常「main」java.lang.NullPointerException'。 – 65535