簡體   English   中英

檢查資源是否已經存在(大小寫不同)

[英]Check if a resource already exists with a different case

在向導我創建一個包,並試圖檢查是否有資源已經用不同的情況,以避免存在ResourceException通過拋出org.eclipse.core.internal.resources.Resource#checkDoesNotExist 例如,當我已經創建com.example.test包時嘗試創建com.Example.test包時遇到此異常。 因此,我想檢查軟件包名稱的每個部分。 現有com.Example.test的情況已在我的代碼中處理。

由於方法checkDoesNotExist在內部類中,並且未由IResource聲明,因此它不在公共API中,因此在調用IFolder#create之前,無法使用它進行檢查。 在這種情況下, IResource#exists方法是無用的,因為它區分大小寫。

目前,我有以下解決方案:

/**
 * This method checks if a package or its part exists in the given source folder with a different case.
 * 
 * @param pfr A source folder where to look package in.
 * @param packageName Name of the package, e.g. "com.example.test"
 * @return A String containing path of the existing resource relative to the project, null if the package name has no conflicts.
 * @throws CoreException
 * @throws IOException
 */
public static String checkPackageDoesExistWithDifferentCase(IPackageFragmentRoot pfr, String packageName)
    throws CoreException, IOException
{
    IPath p = pfr.getResource().getLocation();
    String[] packagePathSegments = packageName.split("\\.");
    for (int i = 0; i < packagePathSegments.length; i++)
    {
        p = p.append(packagePathSegments[i]);
        File f = new File(p.toString());
        String canonicalPath = f.getCanonicalPath();
        if (f.exists() && !canonicalPath.equals(p.toOSString()))
            return canonicalPath.substring(pfr.getJavaProject().getResource().getLocation().toOSString().length() + 1);
    }
    return null;
}

關於此解決方案的問題是,它只能在Windows上運行,因為f.exists()在區分大小寫的文件系統上將返回false

如您所指出的那樣,沒有API,但是您可以檢查父資源是否具有相同名稱(不區分大小寫)的成員,如下所示:

IContainer parent = newFolder.getParent();
IResource[] members = parent.members();
for( IResource resource : members ) {
  if( resource.getName().equalsIgnoreCase( newFolder.getName() ) ) {
    ...
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM