2015-06-03 95 views
11

我有这个(剥离代码示例的HTML标签)函数,该函数从CSV中构建HTML表格,但每次尝试运行时都会收到运行时错误它和我不知道为什么。谷歌说,也许编码的东西是错的,但我不知道如何改变它。java.nio.charset.MalformedInputException:输入长度= 1

我的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) 

121线是

lines.forEach(line -> { 

源代码:

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

} 
+0

对于当前(和未来)参考:如果您还告诉我们发生异常的代码行,这非常有用。 –

+0

*我每次尝试运行时都会收到运行时错误*哪个错误?请分享。 –

+1

对不起,添加了例外的相关部分和行号。 – Vega

回答

23

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

Here's a list受支持的编码(对于Oracle JVM无论如何)。 This post表示“Cp1252”是Windows ANSI。

+4

谢谢,它修复了:) - 流 lines = Files.lines(Paths.get(inputFile),Charset.forName(“Cp1252”));你也知道我必须关闭我的Stream吗? Eclipse会警告我有关资源泄漏的问题,因为我没有调用lines.close(),但我不知道该把它放在哪里,试过finally {}块,但是这给了我一个例外,因为它似乎太早关闭了Stream 。 – Vega

+4

您可以使用try-with-resources在完成使用后自动关闭流:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html尝试(流 lines =文件。行(Paths.get(inputFile),Charset.forName(“Cp1252”)){...您的解析代码在这里...} – blazetopher

+0

完美,它的工作原理非常感谢,现在我可以去睡觉,那是最后一个“bug”,它就像一个魅力。 – Vega