0

我正在尝试读取文件并将其写入特定文件夹。我正在使用这段代码:

private void saveFile(File file){
    try {
        OutputStream out = new FileOutputStream(new File("/Users/default/Desktop/fotos/test.png"));
        Files.copy(file.toPath(), out);
                System.exit(0);

    } catch (IOException ex) {
        Logger.getLogger(GetFiles.class.getName()).log(Level.SEVERE, null, ex);
    }
}

该文件是一个 .png 文件。如果我使用这种方法,它将在 fotos 目录中创建一个新的 .png,但是当我双击它时,它说它是空的。这怎么可能,我该如何解决?

4

1 回答 1

4

您没有关闭输出流。因此,在写入磁盘之前缓冲在其中的任何数据都将丢失。

您可以使用 try-with-resources 语句自动关闭流 - 或者您可以只使用:

// Alternatives, pass in the `File` to copy to, or make the method generally
// more flexible in other ways.
Files.copy(file.toPath(), Paths.get("/Users/default/Desktop/fotos/test.png"));

顺便说一句,调用这样的方法是不寻常System.exit的——它不像方法是saveFileAndTerminateApplication. 同样,您的异常“处理”也不理想。我基本上会让异常冒泡,即声明你的方法抛出它。目前,有三种可能:

  • 一切正常,应用程序终止
  • 副本有效,但System.exit引发未经检查的异常
  • 复制失败,所以方法返回 - 调用者可以推断出了问题,但不知道是什么

对我来说,这听起来不像是一组明显的结果......

于 2015-03-01T22:06:49.257 回答