2013-12-09 36 views
1

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

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

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

+7

你是什么意思写使用IOUtils.toByteArray(InputStream的输入)通过“返回文件”?你是否知道'File'实际上只是一个文件名的包装,甚至可能不存在?也许你真的想返回文件的*内容*,作为字节数组,字符串列表或类似的东西? –

+0

而在Unix系统上,您可以打开文件并返回一些打开的句柄,但Windows不会让您删除打开的文件。 – chrylis

回答

2

你不能把删除的文件的文件句柄,而可以保持数据的字节阵列暂时删除的文件,然后返回字节数组

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(); 

您可以构建从字节数组文件数据

但是,我的建议是从Jakarta commons,你为什么要重新时候就已经在板

+0

考虑将读取放入循环中。 –

0

假设你想要的文件返回给浏览器,这是我做的:

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; 
}