Java 如何返回和删除文件?

Java 如何返回和删除文件?,java,java-io,Java,Java Io,我想从方法返回文件(读取或加载),然后删除此文件 public File method() { File f = loadFile(); f.delete(); return f; } 但当我删除一个文件时,我会从磁盘中删除它,然后在返回语句中只存在到不存在文件的描述符。那么最有效的方法是什么。假设您想将文件返回到浏览器,我就是这样做的: File pdf = new File("file.pdf"); if (pdf.exists()) { try { I

我想从方法返回文件(读取或加载),然后删除此文件

public File method() {
    File f = loadFile();
    f.delete();
    return f;
}

但当我删除一个文件时,我会从磁盘中删除它,然后在返回语句中只存在到不存在文件的描述符。那么最有效的方法是什么。

假设您想将文件返回到浏览器,我就是这样做的:

File pdf = new File("file.pdf");
if (pdf.exists()) {
  try {
    InputStream inputStream = new FileInputStream(pdf);
    httpServletResponse.setContentType("application/pdf");
    httpServletResponse.addHeader("content-disposition", "inline;filename=file.pdf");
    copy(inputStream, httpServletResponse.getOutputStream());
    inputStream.close();
    pdf.delete();
  } catch (Exception e) {
    e.printStackTrace();
  } 
}

private static int copy(InputStream input, OutputStream output) throws IOException {
  byte[] buffer = new byte[512];
  int count = 0;
  int n = 0;
  while (-1 != (n = input.read(buffer))) {
      output.write(buffer, 0, n);
      count += n;
  }
  return count;
}

您不能保留已删除文件的文件句柄,而是可以暂时将数据保留在字节数组中,删除文件,然后返回字节数组

public byte[] method() {
   File f =loadFile();
                FileInputStream fis = new FileInputStream(f);
                byte[] data = new byte[fis.available()];
                fis.read(data);
                f.delete();
    return data;
}
//编辑附件2

                FileInputStream input = new FileInputStream(f);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int bytesRead = input.read(buf);
                while (bytesRead != -1) {
                    baos.write(buf, 0, bytesRead);
                  bytesRead = input.read(buf);
                }
                baos.flush();
                byte[] bytes = baos.toByteArray();
您可以从字节数组构造文件数据

public byte[] method() {
   File f =loadFile();
                FileInputStream fis = new FileInputStream(f);
                byte[] data = new byte[fis.available()];
                fis.read(data);
                f.delete();
    return data;
}

然而,我的建议是使用IOUtils.toByteArray(InputStream input)from,当已经在板中时,为什么要重新写入?您是否知道
File
实际上只是一个文件名的包装器,它甚至可能不存在?也许您真的想返回文件的内容,如字节数组、字符串列表或类似的内容?在Unix系统上,您可以打开文件并返回某种类型的打开句柄,但Windows不允许删除打开的文件。