When I check the "Dir" directory, the file is created properly (with name writtenfile1), but nothing gets written inside and I do not understand why.

Is this a common pitfall with BufferedWriter? Because my code looks perfectly reasonable.

    int i = 1;
    Path path = Paths.get("Dir//writtenfile" + i + ".txt");
    Charset charset = Charset.defaultCharset();
    try {
        BufferedWriter writer = Files.newBufferedWriter(path, charset);
        writer.write("Message written!");
        //writer.write("This is file number " + i);
    } catch (Exception e) {
        System.out.println(e);
    }
有帮助吗?

解决方案

As the name BufferedWriter implies, the data is buffered. It or the last part is only written on explicitly flushing or closing the writer instance.

This is not a bug; it is normal behaviour of this class.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top