在我的例子中,有效的CSV是用逗号或分号分隔的。我对其他库开放,但它需要是Java。通过Apache CSVParser API阅读,我唯一能想到的就是这样做看起来既低效又难看。
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
CSVFormat csvFormat = CSVFormat.EXCEL.withHeader().withDelimiter(';');
CSVParser parser = csvFormat.parse( reader );
// now read the records
}
catch (IOException eee)
{
try
{
// try the other valid delimeter
csvFormat = CSVFormat.EXCEL.withHeader().withDelimiter(',');
parser = csvFormat.parse( reader );
// now read the records
}
catch (IOException eee)
{
// then its really not a valid CSV file
}
}
有没有办法首先检查分隔符,或者可能允许两个分隔符?任何人都有一个比捕捉异常更好的想法吗?
答案 0 :(得分:4)
我们在uniVocity-parsers中建立了对此的支持:
public static void main(String... args) {
CsvParserSettings settings = new CsvParserSettings();
settings.setDelimiterDetectionEnabled(true);
CsvParser parser = new CsvParser(settings);
List<String[]> rows = parser.parseAll(file);
}
解析器还有更多功能,我相信您会发现它们非常有用。试一试。
免责声明:我是这个图书馆的作者,它的开源和免费(apache 2.0许可证)
答案 1 :(得分:0)
我遇到了同样的问题,我是这样解决的:
BufferedReader in = Files.newBufferedReader(Paths.get(fileName));
in.mark(1024);
String line = in.readLine();
CSVFormat fileFormat;
if(line.indexOf(';') != -1)
fileFormat = CSVFormat.EXCEL.withDelimiter(';');
else
fileFormat = CSVFormat.EXCEL;
in.reset();
之后你可以用 CSVParser
解析它。
答案 2 :(得分:0)
下面是我对这个问题的解决:
index.ts:9:16 - error TS2344: Type 'T[K]' does not satisfy the constraint 'RecursiveRecord'.
Type 'T[string]' is not assignable to type 'RecursiveRecord'.
Type 'string | RecursiveRecord' is not assignable to type 'RecursiveRecord'.
Type 'string' is not assignable to type 'RecursiveRecord'.
示例用法:
private static final Character[] DELIMITERS = {';', ','};
private static final char NO_DELIMITER = '\0'; //empty char
private char detectDelimiter() throws IOException {
try (
final var reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
) {
String line = reader.readLine();
return Arrays.stream(DELIMITERS)
.filter(s -> line.contains(s.toString()))
.findFirst()
.orElse(NO_DELIMITER);
}
}