我正在尝试删除一个文件,在写完文件后,用FileOutputStream.这是我用来编写的代码:
private void writeContent(File file, String fileContent) {
FileOutputStream to;
try {
to = new FileOutputStream(file);
to.write(fileContent.getBytes());
to.flush();
to.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
如图所示,我刷新并关闭流,但是当我尝试删除时,file.delete()返回false.
我删除前检查,看看是否该文件存在,并且:file.exists(),file.canRead(),file.canWrite(),file.canExecute()所有返回true.在调用这些方法后,我尝试file.delete()返回false.
有什么我做错了吗?
我目前在Java代码中遇到了FileOutputStream的问题.
实际上我使用FileOutputStream来创建文件,但是一旦创建了文件,就无法删除它.据我所知,这可能来自FileOutputstream未关闭的事实.
在我的汇总代码下面:
outFile = new FileOutputStream(dir+"\\"+fileName);
outFile.write("Test");
outFile.flush();
outFile.close();
outFile = null;
System.gc();
Run Code Online (Sandbox Code Playgroud)
然后就没有办法删除文件,即使是"手动".当我的程序启动时,我无法通过简单的del在Windows上删除它.我还试图删除文件夹目录的内容,但它也没有用,使用此代码:
static public void delDir( String place )
{
File path = new File( place );
System.out.println(path.exists());//return true
if( path.exists() )
{
File[] f = path.listFiles();
for( int j = 0 ; j < f.length ; j++ )
{
if( f[ j ].isDirectory() )
{
deleteDirectory( path+"\\"+f[ j ] );
}
f[ j ].delete();
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是: 如何关闭此文件以进行下一次删除(或者如果我们无法关闭它,如何正确删除它)?