简体   繁体   中英

Check if a resource already exists with a different case

In a wizard I am creating a package and trying to check if a resource already exists with a different case to avoid ResourceException thrown by org.eclipse.core.internal.resources.Resource#checkDoesNotExist . For example I get this exception when I try to create a package com.Example.test while com.example.test already exist. So I would like to make a check for the every segment of the package name. The case for existing com.Example.test is already handled in my code.

Since the method checkDoesNotExist is in the internal class and not declared by IResource it's not in the public API and I cannot use it to make the check before calling IFolder#create . The method IResource#exists is useless in this case because it's case sensitive.

Currently I have the following solution:

/**
 * 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;
}

The issue about this solution is that it would work only on Windows, since f.exists() would return false on case-sensitive filesystems.

As you pointed out, there is not API, but you can check the parent resource if it has a member with the same (case-insensitive) name like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM