java.nio.charset.MalformedInputException: 输入长度 = 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30609062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.nio.charset.MalformedInputException: Input length = 1
提问by Vega
I have this (stripped the HTML tags for the code example) function that builds a HTML table out of a CSV, but I get a runtime error everytime I try to run it and I don't know why. Google says that maybe something with the encoding is wrong but I have no idea how to change that.
我有这个(去除了代码示例的 HTML 标签)函数,它从 CSV 中构建了一个 HTML 表,但是每次我尝试运行它时都会出现运行时错误,我不知道为什么。谷歌说可能编码有问题,但我不知道如何改变它。
My CSV is encoded in ANSI and contains characters like ?, ?, ü, ? but I have no control over the encoding or if it will change in the future.
我的 CSV 是用 ANSI 编码的,包含像 ?, ?, ü, ? 但我无法控制编码,或者将来是否会改变。
The error occurs here:
错误发生在这里:
Caused by: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
at java.io.BufferedReader.hasNext(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.ReferencePipeline$Head.forEach(Unknown Source)
at testgui.Csv2Html.start(Csv2Html.java:121)
Line 121 is
第 121 行是
lines.forEach(line -> {
Sourcecode:
源代码:
protected void start() throws Exception {
Path path = Paths.get(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile, true);
PrintStream ps = new PrintStream(fos);
boolean withTableHeader = (inputFile.length() != 0);
try {
Stream<String> lines = Files.lines(path);
lines.forEach(line -> {
try {
String[] columns = line.split(";");
for (int i=0; i<columns.length; i++) {
columns[i] = escapeHTMLChars(columns[i]);
}
if (withTableHeader == true && firstLine == true) {
tableHeader(ps, columns);
firstLine = false;
} else {
tableRow(ps, columns);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
});
} finally {
ps.close();
}
}
采纳答案by blazetopher
You can try to utilize the correct encoding by using the Files.lines(Path path, Charset charset)
form of the lines
method (javadocs).
您可以尝试通过使用方法的Files.lines(Path path, Charset charset)
形式lines
( javadocs)来使用正确的编码。
Here's a listof supported encodings (for the Oracle JVM anyhow). This postindicates that "Cp1252" is Windows ANSI.