读入输入流后删除文件

问题描述 投票:0回答:3

我正在尝试从本地存储的文件中检索视频流。读入输入流后,我试图删除该文件,但它不允许这种情况发生。我知道我需要关闭流,但我需要将此流传递给网络服务器调用。关于如何最好地解决这个问题的任何想法:

InputStream is = new FileInputStream("\\Location\\file.txt");
File f = new File("\\Location\\file.txt");

             if(f.delete()) {
                System.out.println("success");
             } else {
                System.out.println("failure");
             }  
java inputstream
3个回答
2
投票

尝试在 Finally 块上删除

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

class DeleteFile extends FileInputStream {

  File file;

  public DeleteFile(String s) throws FileNotFoundException {
    this(new File(s));
  }

  public DeleteFile(File file) throws FileNotFoundException {
    super(file);
    this.file = file;
  }

  public void close() throws IOException {
    try {
      super.close();
    } finally {
      if (file != null) {
        file.delete();
        file = null;
      }
    }
  }
}

2
投票

这是构造函数中发生的事情

FileInputStream(File file)
您的构造函数委托给:

public FileInputStream(File file) throws FileNotFoundException {
   //some checks of file objects omitted here
   fd = new FileDescriptor();
   fd.attach(this);
   open(name);    //native method opening the file for reading
}

调用

FileInputStream.close()
释放在构造函数中创建的文件描述符并调用本地方法关闭打开的文件。

调用

close()
后,您将能够删除文件。

在这里查看来源.


0
投票

Files.newInputStream(yourFile,StandardOpenOption.DELETE_ON_CLOSE)
似乎是一个更好的选择。

© www.soinside.com 2019 - 2024. All rights reserved.