我正在尝试删除一个文件,在写完文件后,用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.
有什么我做错了吗?
我想知道a是否InputStream
为空,但不使用该方法read()
.有没有办法知道它是否是空的而没有从中读取?
通常,此代码用于转换File
为IFile
:
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IPath location= Path.fromOSString(file.getAbsolutePath());
IFile ifile= workspace.getRoot().getFileForLocation(location);
Run Code Online (Sandbox Code Playgroud)
但这仅适用于项目中的java文件.如何获取IFile
when File
文件不在工作区中(不在项目中)?
尝试通过ResourcesPlugin获取工作区时出现此错误:
java.lang.IllegalStateException: Workspace is closed.
at org.eclipse.core.resources.ResourcesPlugin.getWorkspace(ResourcesPlugin.java:339)
Run Code Online (Sandbox Code Playgroud)
生成它的代码是:
IWorkspace ws = ResourcesPlugin.getWorkspace();
Run Code Online (Sandbox Code Playgroud)
你能帮忙解决这个问题吗?