Java Path Relative Get getRelativePath(final File parentDir, final File file)

Here you can find the source of getRelativePath(final File parentDir, final File file)

Description

get Relative Path

License

Apache License

Declaration

private static String getRelativePath(final File parentDir, final File file) 

Method Source Code

//package com.java2s;
/*/*from   w w  w  . ja va2  s  .  co m*/
 * Copyright (c) 2015, Haiyang Li.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

import java.io.IOException;

public class Main {
    private static String getRelativePath(final File parentDir, final File file) {
        if (file.equals(parentDir)) {
            return file.getName();
        } else {
            return file.getAbsolutePath().substring(parentDir.getAbsolutePath().length() + 1);
        }
    }

    private static String getAbsolutePath(final File parentDir, String relativeFilePath) throws IOException {
        String newRelativePath = "";

        for (int i = 0; i < relativeFilePath.length(); i++) {
            char c = relativeFilePath.charAt(i);

            if ((c == '\\') || (c == '/')) {
                newRelativePath += File.separator;
            } else {
                newRelativePath += c;
            }
        }

        relativeFilePath = newRelativePath;

        String path = parentDir.getAbsolutePath() + File.separator + relativeFilePath;

        File dir = new File(path.substring(0, path.lastIndexOf(File.separator)));

        if (!dir.exists()) {
            dir.mkdirs();
        }

        return path;
    }
}

Related

  1. getRelativePath(final File baseDirectory, final File f)
  2. getRelativePath(final File basePathFile, final File pathFile)
  3. getRelativePath(final File file, final File folder)
  4. getRelativePath(final File from, final File to)
  5. getRelativePath(final File fromFile, final File toFile)
  6. getRelativePath(final File parentDirectory, final File file)
  7. getRelativePath(final String base, final File targetFile)
  8. getRelativePath(String base, String fullPath)
  9. getRelativePath(String base, String relative, boolean isBaseFile)