java.nio.charset.MalformedInputException:输入长度= 1

Veg*_*ega 17 java io character-encoding malformed

我有这个(剥离代码示例的HTML标签)函数,用CSV构建HTML表格,但每次尝试运行它时都会出现运行时错误,我不知道为什么.谷歌说,编码的东西可能是错误的,但我不知道如何改变它.

我的CSV以ANSI编码,包含ä,Ä,Ü,Ö等字符,但我无法控制编码或将来是否会发生变化.

这里发生错误:

Caused by: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
at java.io.BufferedReader$1.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)
Run Code Online (Sandbox Code Playgroud)

第121行是

lines.forEach(line -> {
Run Code Online (Sandbox Code Playgroud)

源代码:

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

bla*_*her 31

您可以尝试使用方法的Files.lines(Path path, Charset charset)形式lines(javadocs)来使用正确的编码.

这是一个支持的编码列表(无论如何,对于Oracle JVM). 这篇文章表明"Cp1252"是Windows ANSI.

  • 谢谢,修复它:) - Stream <String> lines = Files.lines(Paths.get(inputFile),Charset.forName("Cp1252")); 你也知道我在哪里关闭我的流吗?Eclipse警告我关于ressource泄漏,因为我不调用lines.close()但是我不知道在哪里放置它,尝试了finally {}块但是这给了我一个例外,因为它似乎我太早关闭了Stream . (4认同)
  • 您可以使用try-with-resources在完成使用后自动关闭流:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html try(Stream <String> lines = Files .lines(Paths.get(inputFile),Charset.forName("Cp1252")){...这里的解析代码...} (4认同)