如何在java中保存文件 [英] How to save a file in java

查看:2688
本文介绍了如何在java中保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从日志报告中创建一个文件。为了保存,我创建了一个按钮。按下按钮时,将执行以下代码。

I am trying to create a file from a log report. To save I have created a button. When the button is pushed, the following code is executed.

public void SAVE_REPORT(KmaxWidget widget){//save
  try {
    String content = report.getProperty("TEXT");
    File file = new File("logKMAX.txt");
    // if file doesnt exists, then create it
    if (!file.exists()) {
      file.createNewFile();
    }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
} //SAVE_REPORT

我没有编译错误,但又一次目录中没有文件保存,我有上述代码。

I have no compile errors, but again there is no file save in the directory that I have the aforementioned code.

有什么可能出错的想法吗?

Any idea on what might be wrong?

推荐答案

使用新文件API。首先,在你的程序中,你不验证 .createNewFile()的返回值:它在失败时不会抛出异常......

Use the new file API. For one, in your program, you don't verify the return value of .createNewFile(): it doesn't throw an exception on failure...

使用新的文件API,它更简单:

With the new file API, it is MUCH more simple:

public void saveReport(KmaxWidget widget)
    throws IOException
{
    final String content = report.getProperty("TEXT");
    final Path path = Paths.get("logKMAX.txt");

    try (
        final BufferedWriter writer = Files.newBufferedWriter(path,
            StandardCharsets.UTF_8, StandardOpenOption.CREATE);
    ) {
        writer.write(content);
        writer.flush();
    }
}

这篇关于如何在java中保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆