Search code examples
javafilefilewriter

MalformedInputException: Input length = 1 when run over twice


Running over a File with this Code works just fine the first time, but on a second Run (on the same File), Files.readAllLines throws said Exception.

All the code does is (for each file but in this case it's just one) get all the lines from a file, delete it, and then refill it with the same content.

for (File file : content) {
    List<String> fillLines = new ArrayList<>();
    try {
        fillLines = Files.readAllLines(file.toPath());
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (fillLines.size() > 0) {
        file.delete();
        FileWriter fileWriter = new FileWriter(file, false);

        for (String line : fillLines) {
            fileWriter.write(line);
            if (fillLines.indexOf(line) < fillLines.size() - 1)
                fileWriter.append(System.lineSeparator());
        }
        fileWriter.close();
    }
}

Any ideas? Might be because of fileWriter.append(System.lineSeparator());?

All the other Questioneers were failing the first time because of reading it with a wrong charset. But as I'm able to run it once, I'm not reading but writing something wrong, so changing the charset seems like a workaround that could be avoided.

Stacktrace:

java.nio.charset.MalformedInputException: Input length = 1
    at java.nio.charset.CoderResult.throwException(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.nio.file.Files.readAllLines(Unknown Source)
    at java.nio.file.Files.readAllLines(Unknown Source)

anything below here points to

    fillLines = Files.readAllLines(file.toPath());

Solution

  • From the documentation of Files.readAllLines():

    Bytes from the file are decoded into characters using the UTF-8 charset

    From the documentation of FileWriter:

    The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

    So, you're writing using the default platform encoding (which, in your case, is not UTF8), and reading with UTF8. That is the cause of the exception. Use the same encoding to write and read. The above documentation explains how to specify the UTF8 encoding to write.