创建文件夹和创建文件具有相同的编程模式。首先,获取资源的句柄,然后判断该资源是否存在,如果不存在,则可以创建该资源。通常,您可以从文件夹或项目获取一个文件夹或文件的句柄。如果请求的是一个已存在的资源,那么您已经获得一个可以直接使用的资源。如果请求的资源并不存在,那么需要创建该资源。但有一个前提必须满足:该资源的父资源必须是可访问的。
下面的代码根据名称获取项目的一个文件夹,如果该文件夹不存在,则试图创建该文件夹。
private void createFolderInProject (IProject project, String folderName) {
IFolder newFolder = project.getFolder(folderName);
if (!newFolder.exists()) {
try{
newFolder.create(true,true,null);
} catch (CoreException e) {
//... ...
//Deal with Operation
}
}
}
tips:
在获取句柄、创建文件夹的过程中,文件系统有可能已经具有一个同名的文件夹,或者所给的文件夹名不合法。你就必须考虑自己的资源创建策略。在这个例子中,你可以先检查项目是否已经与文件系统同步,但这也只能避免一些可能的麻烦。
当文件系统中包含未被工作空间所感知到资源时,您所设计的创建策略,需要补货活避免常见错误。对于这一点,Workbench New Folder向导使用的一种混合策略:在处理创建请求之前,先检查文件夹名是否合法,如果文件夹已经存在u文件系统中,则创建失败。
下面代码用来展示如何在传入参数所指定的文件夹下创建一个文件。如果文件已经存在,则它的内容将会被替换。其中的getInitialContents方法用来提供新文件的内容或者替换现有文件的内容。
private void createFileInFolder(IFolder folder) {
IFile newFile = folder.getFile("new_File.txt");
try{
if(newFile.exists())
newFile.setContents(getInitialContents(), true, false, null);
else
java.io.File systemFile = newFile.getLocation().toFile();
if(systemFile.exists()) {
// skip create -- in file system
// could refreshLocal on parent at this point
}else{
newFile.create(getInitialContents(), false, null;)
}
}catch(CoreException e){
e.printStackTrace();
}
}
// Return input stream used to create initial file contents.
private InputStream getInitialContents() {
StringBuffer sb = new StringBuffer();
sb.append("My New File Contents");
return new ByteArrayInputStream(sb.toString().getBytes());
}