请考虑以下示例Java类(下面的pom.xml):
package test.filedelete;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import org.apache.commons.io.IOUtils;
public class Main
{
public static void main(String[] args) throws IOException
{
byte[] bytes = "testtesttesttesttesttesttesttesttesttest".getBytes();
InputStream is = new ByteArrayInputStream(bytes);
Path tempFileToBeDeleted = Files.createTempFile("test", "");
OutputStream os = Files.newOutputStream(tempFileToBeDeleted);
IOUtils.copy(is, os);
deleteAndCheck(tempFileToBeDeleted);
// breakpoint 1
System.out.println("\nClosing stream\n");
os.close();
deleteAndCheck(tempFileToBeDeleted);
}
private static void deleteAndCheck(Path file) throws IOException
{
System.out.println("Deleting file: " + file);
try
{
Files.delete(file);
}
catch (NoSuchFileException e)
{
System.out.println("No such file");
}
System.out.println("File really deleted: " + !Files.exists(file));
System.out.println("Recreating deleted file ...");
try
{
Files.createFile(file);
System.out.println("Recreation successful");
}
catch (IOException e)
{
System.out.println("Recreation not possible, exception: " + e.getClass().getName());
}
}
}
我写入一个FileOutputStream,并尝试删除该文件,而不关闭Stream首先.这是我原来的问题,当然是错误的,但是它导致了一些奇怪的观察.
当您在Windows 7上运行主方法时,会生成以下输出:
Deleting file: C:\Users\MSCHAE~1\AppData\Local\Temp\test6100073603559201768
File really deleted: true
Recreating deleted file ...
Recreation not possible, exception: java.nio.file.AccessDeniedException
Closing stream
Deleting file: C:\Users\MSCHAE~1\AppData\Local\Temp\test6100073603559201768
No such file
File really deleted: true
Recreating deleted file ...
Recreation successful
>为什么第一次调用Files.delete()不会引发异常?
>为什么以下调用Files.exist()返回false?
>为什么不能重新创建文件?
关于最后一个问题,我注意到当您在断点1停止时,资源管理器中的文件仍然可见.当您终止JVM时,该文件将被删除.关闭流后,deleteAndCheck()将按预期方式工作.
在我看来,删除不会在关闭流之前传播到操作系统,而且文件API没有正确反映出来.
有人可以准确地解释这里发生了什么吗?
的pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
test
filedelete
0.0.1-SNAPSHOT
commons-io
commons-io
2.4
更新澄清
Windows资源管理器中的文件消失,如果流被关闭并且调用了Files.delete() – 最后一个操作触发器,或者如果已经调用Files.delete()而不关闭流并且JVM被终止.