Relative path to file.

@param self the <code>File</code> to calculate the path from
@param to   the <code>File</code> to calculate the path to
@return the relative path between the files
766152
public static String relativePath(File self, File to) throws IOException {
        String fromPath = self.getCanonicalPath();
        String toPath = to.getCanonicalPath();

        // build the path stack info to compare
        String[] fromPathStack = getPathStack(fromPath);
        String[] toPathStack = getPathStack(toPath);

        if (0 < toPathStack.length && 0 < fromPathStack.length) {
            if (!fromPathStack[0].equals(toPathStack[0])) {
                // not the same device (would be "" on Linux/Unix)

                return getPath(Arrays.asList(toPathStack));
            }
        } else {
            // no comparison possible
            return getPath(Arrays.asList(toPathStack));
        }

        int minLength = Math.min(fromPathStack.length, toPathStack.length);
        int same = 1; // Used outside the for loop

        // get index of parts which are equal
        while (same < minLength && fromPathStack[same].equals(toPathStack[same])) {
            same++;
        }

        List<String> relativePathStack = new ArrayList<String>();

        // if "from" part is longer, fill it up with ".."
        // to reach path which is equal to both paths
        for (int i = same; i < fromPathStack.length; i++) {
            relativePathStack.add("..");
        }

        // fill it up path with parts which were not equal
        relativePathStack.addAll(Arrays.asList(toPathStack).subList(same, toPathStack.length));

        return getPath(relativePathStack);
    }
108124
public static void mkParentDirs(final File file) throws IOException {
        // Create parent directory structure if necessary
        File parentFile = file.getParentFile();
        if (parentFile == null) {
            // File was created with a relative path
            parentFile = file.getAbsoluteFile().getParentFile();
        }
        if (parentFile != null && !parentFile.exists()) {
            if (!parentFile.mkdirs()) {
                throw new IOException("Unable to create parent directory " +
                        "structure for file " + file.getAbsolutePath());
            }
        }
    }
822911
public String relativePath(File base, File nested) throws IOException {
        String basePath = base.getCanonicalPath();
        String nestedPath = nested.getCanonicalPath();
        if (nestedPath.equals(basePath)) {
            return "";
        } else if (nestedPath.startsWith(basePath)) {
            return nestedPath.substring(basePath.length() + 1);
        } else {
            return nestedPath;
        }
    }
1027465
public static byte[] fileToBytes(Object testClass, String relativePath) {
		try {
			URL url = testClass.getClass().getResource(relativePath);
			if (url == null) {
				throw new FileNotFoundException(relativePath);
			}
			return Files.readAllBytes(Paths.get(url.toURI()));
		}
		catch (IOException | URISyntaxException ex) {
			throw new IllegalStateException(ex);
		}
	}
752322
public static String getRelativePath(File file, File srcDir) {

		String base = srcDir.getPath();
		String filePath = file.getPath();

		String relativePath = new File(base).toURI()
				.relativize(new File(filePath).toURI()).getPath();
		return relativePath;
	}
1203651
public static boolean walkPath(File appRoot, String relativePath) throws IOException {
        // Walk the path from the app root
        String[] relativePathElements = relativePath.replace(File.separatorChar, '/').split("/");
        File currentPath = new File(appRoot.getCanonicalPath());
        for (int i = 0; i < relativePathElements.length; i++) {        	
    		// Handle urls which start with a "/" in whoich case split  
    		if (!relativePathElements[i].equals("")) {
                String[] entries = currentPath.list(new StrictFileNameFilter(relativePathElements[i]));
                if (entries==null || entries.length != 1) {
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) 
                        logger.logp(Level.FINE, CLASS_NAME,"uriCaseCheck",relativePathElements[i] + " not found.");
                    return false;
                }
                currentPath = new File(currentPath, relativePathElements[i]);
    		}    
        }
        return true;
    }
324637
def path_to_url(path, relative_to = nil)

      # Find the parent path we're in
      path = Pathname.new(path).realpath
      base = self.load_paths.find{|lp| path.to_s =~ /\A#{Regexp.escape(lp.realpath.to_s)}/ }

      path = path.relative_path_from(base).cleanpath
      
      if relative_to
        if relative_to.to_s =~ /\A\//
          relative_to = Pathname.new(File.dirname(relative_to.to_s)).relative_path_from(base).cleanpath
        else
          relative_to = Pathname.new(File.dirname(relative_to.to_s))
        end
        path = Pathname.new("/" + path.to_s).relative_path_from(Pathname.new("/" + relative_to.to_s))
        path.to_s
      else
        "/" + path.to_s
      end
      
    end
127375
public static DocPath relativePath(PackageDoc from, PackageDoc to) {
        return forRoot(from).resolve(forPackage(to));
    }
75382
public static void copy(String fromFile, String toFile) throws IOException {

        File inputFile = new File(fromFile);
        File outputFile = new File(toFile);
        if (!outputFile.getParentFile().isDirectory()) {
            outputFile.getParentFile().mkdirs();
        }
        FileInputStream in = new FileInputStream(inputFile);
        FileOutputStream out = new FileOutputStream(outputFile);

        // transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
1101259
@Override
    public ICodeBaseLocator createRelativeCodeBaseLocator(String relativePath) {
        File path = new File(pathName);
        if (!path.isDirectory()) {
            path = path.getParentFile();
        }
        File relativeFile = new File(path, relativePath);
        return new FilesystemCodeBaseLocator(relativeFile.getPath());
    }
673289
@Override
    public File getFile() throws IOException {
        try {
            return this.path.toFile();
        } catch (UnsupportedOperationException ex) {
            // only Paths on the default file system can be converted to a File
            // do exception translation for cases where conversion is not possible
            throw new FileNotFoundException(this.path + " cannot be resolved to " + "absolute file path");
        }
    }
758976
@Override
    public Path toAbsolutePath() {

        // Already absolute?
        if (this.isAbsolute()) {
            return this;
        }

        // Else construct a new absolute path and normalize it
        final Path absolutePath = new ShrinkWrapPath(ArchivePath.SEPARATOR + this.path, this.fileSystem);
        final Path normalized = absolutePath.normalize();
        return normalized;
    }
557881
@SuppressWarnings("deprecation")
    @Override
    public File getFile(String path, boolean nativeCode) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, " asked to getFile for path " + path);

        path = preSlashify(path);
        if (path.equals("/")) {
            // return a file for "/" .. for normal bundles this would be the jar
            // or directory. For loose, we might have a dir mapped to root, or may not
            // if we do, we'll try using it.
            if (container.getPhysicalPath() != null)
                return new File(container.getPhysicalPath());
            else
                return null;
        }
        final Entry entry = container.getEntry(path);
        if (entry == null) {
            //no entry found for path, bundle has been asked for a file/path that doesn't exist.
            //can happen via bundle-classpath entries for paths that don't exist in the bundle.
            return null;
        }
        Container entryContainer = getContainer(entry);
        if (entryContainer == null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, " returning file for entry at " + path + " @ " + entry.getPhysicalPath());

            // this is a 'normal entry' we are going to assume we can get a real file
            // we are allowed to use getPhysicalPath, as this layer has to see through the abstraction for
            // leaf nodes that are files.
            final String physical = entry.getPhysicalPath();
            if (physical != null) {
                return AccessController.doPrivileged(new PrivilegedAction<File>() {
                    @Override
                    public File run() {
                        return new File(physical);
                    }

                });
            }
            // TODO Going to have to extract the content out to a file on disk

            // This would be a case where an entry in a container has no physical path. 
            // If loose config allowed jars to be mapped as directories, this would occur there.

            // Jars mapped as files are already handled by equinox natively, so the lack of 
            // physical paths there will not cause issues.

            // The other common source of imaginary physical paths is intermediate directory 
            // creation..  
            // (eg, mapping /etc/fred.txt as /etc/fish/goat/horse/fred.txt and asking for physical path of 'goat')

            // Current artifact implementations always have a physical path, but this may not remain true 
            // forever, so this case DOES need to be handled, else we'll have some very entertaining 
            // bugs to handle for future deployment types. 
            return null;
        }

        if (nativeCode) {
            // native code is not supported as a container
            return null;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, " entry was a container.. but was it root? " + entryContainer.isRoot());
        if (!entryContainer.isRoot()) {
            // If the container is not a root then it is 
            // a simple directory in an archive; just return null.
            // The framework will handle nested directories in archives
            return null;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, " leaf node was a root container, so use marker file for equinox");

        // This is a root container and may be on the bundle classpath.
        // Need to create a temp file to return so we can find this container later when a bundle file is created
        final File tempBase = context.getDataFile("nestedTempFiles");
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, " creating a temp dir, request was for " + path + " the nested path");

        // create the temp dir, if needed.. not clear
        if (!AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
            @Override
            public Boolean run() {
                return tempBase.exists() || tempBase.mkdirs();
            }
        })) {
            //no chained exception will mean mkdirs failed.
            throw new IllegalStateException();
        }
        try {
            File t = null;
            try {
                t = AccessController.doPrivileged(new PrivilegedExceptionAction<File>() {
                    @Override
                    public File run() throws IOException {
                        return File.createTempFile(entry.getName(), null, tempBase);
                    }
                });
            } catch (PrivilegedActionException e) {
                Exception e2 = e.getException();
                if (e2 instanceof IOException)
                    throw (IOException) e2;
                if (e2 instanceof RuntimeException)
                    throw (RuntimeException) e2;
                throw new UndeclaredThrowableException(e);
            }
            final File tempKey = t;

            // Add it to the nestedFiles map so that the ModuleBundleFileFactory impl can
            // find the container if the framework attempts to create a bundle file from it.
            nestedFiles.put(tempKey, entryContainer);
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    tempKey.deleteOnExit();
                    return null;
                }
            });

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, " returning a tempkey file.. " + tempKey.getAbsolutePath());
            return tempKey;
        } catch (IOException e) {
            //chained exception will mean the temp create failed.
            throw new IllegalStateException(e);
        }
    }
1265942
private static String getRelativePath(File src, File target) {
        String[] srcComponents = getCanonicalPath(src).replace(File.separatorChar, '/').split("/");
        String[] targetComponents = getCanonicalPath(target).replace(File.separatorChar, '/').split("/");

        if (srcComponents.length > 0 && targetComponents.length > 0 && !targetComponents[0].equals(srcComponents[0])) {
            return null;
        }

        int common = 0;
        for (int minLength = Math.min(srcComponents.length, targetComponents.length); common < minLength; common++) {
            if (!srcComponents[common].equals(targetComponents[common])) {
                break;
            }
        }

        StringBuilder result = new StringBuilder();

        // Paths in a file are relative to the file's directory, so subtract one
        // to skip the final filename component.
        for (int i = common; i < srcComponents.length - 1; i++) {
            if (result.length() != 0) {
                result.append('/');
            }
            result.append("..");
        }

        for (int i = common; i < targetComponents.length; i++) {
            if (result.length() != 0) {
                result.append('/');
            }
            result.append(targetComponents[i]);
        }

        return result.toString();
    }
282943
@Override
    public String getPath() {
    	String result;

    	result = path.toString().substring(getRoot().getAbsolute().length());
    	return result.replace(File.separatorChar, Filesystem.SEPARATOR_CHAR);
    }
1343519
public static String path(String file) {
      if (StringUtils.isNullOrBlank(file)) {
         return StringUtils.EMPTY;
      }
      file = StringUtils.trim(file);
      int pos = indexOfLastSeparator(file);
      return pos == file.length() - 1 ? file.substring(0, file.length() - 1) : file;
   }
1163136
public static String getPathToBase() {
		String path = new File(".").getAbsoluteFile().getParent();

		while( path != null )  {
			File f = new File(path);
			if( !f.exists() )
				break;

			String[] files = f.list();
			if( files == null )
				break;

			boolean foundMain = false;
			boolean foundExamples = false;
			boolean foundIntegration = false;

			for( String s : files ) {
				if( s.compareToIgnoreCase("main") == 0 )
					foundMain = true;
				else if( s.compareToIgnoreCase("examples") == 0 )
					foundExamples = true;
				else if( s.compareToIgnoreCase("integration") == 0 )
					foundIntegration = true;
			}

			if( foundMain && foundExamples && foundIntegration)
				return path;

			path = f.getParent();
		}
		return null;
	}