Java BufferedWriter不写入文件

时间:2018-05-01 13:31:04

标签: java bufferedwriter

我想写一些字符串到文件(使用Java 8)。这段代码片段没有任何错误编译,但没有写入文件....我是noob ofcorz ...有什么建议吗?

import java.io.BufferedWriter;
import java.io.FileWriter;

public class Main {
    private static final String FILENAME = "C:\\IntelliJfiles\\write-to- 
                                              file\\src\\pl\\sca\\file.txt";

    public static void main(String[] args) {

        try {
            String str = "kal";

            BufferedWriter writer = new BufferedWriter(new 
            FileWriter(FILENAME));
            writer.write(str);

            System.out.println("Done");

        }
        catch (Exception e) {
            System.out.println("There's no file");
            e.printStackTrace();
        }
    }
}

4 个答案:

答案 0 :(得分:2)

在关闭文件之前,它可能无法写入文件 - 写入磁盘非常耗时,因此在将实际文件放入文件之前等待写入足够的字符。那是BufferedWriter中缓冲的含义。如果你关闭它,它将"冲洗"缓冲区到磁盘上。

您可以使用writer.close()

自行关闭它

或者您可以使用try-with-resources,它会自动关闭作者:

try (FileWriter fw = new FileWriter("C:\\IntelliJfiles\\write-to-file\\src\\pl\\sca\\file.txt");
     BufferedWriter bw = new BufferedWriter(fw)){
    bw.write("kal");
} catch (Exception e) {
    e.printStackTrace();
}

答案 1 :(得分:0)

您需要关闭作者,您可以使用try-with-resources

String str = "kal";

// we can use try-with-resources from java 7
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILENAME))) {
    writer.write(str);
}

System.out.println("Done");

或者只需添加writer.close()

writer.write(str);
writer.close();

答案 2 :(得分:0)

BufferWriter的替代方法是Files.write(Path, byte[], OpenOption...),如果您的目标只是写入一次文件。

String str = "test";
Path path = Paths.get("file.txt");

try {
    byte[] bytes = str.getBytes(StandardsCharsets.UTF_8);
    Files.write(path, bytes);
} catch (FileNotFoundException e) {
    // Handle file absence.
} catch (IOException e) {
    // Handle other exceptions related to io.
}

注意:如上所述here捕捉Exception并不表示在所有情况下都缺少文件。如果您要处理文件缺席,请抓住FileNotFoundException;如果您遇到与io相关的所有异常情况,请IOException

答案 3 :(得分:0)

尝试这个

try {
            String str = "kal";
            BufferedWriter writer = new BufferedWriter(new 
            FileWriter(FILENAME));
            writer.write(str);
            writer.close();
            System.out.println("Done");

        }