Java Is Legal File Path isLegalFilePath(File inBasePath, File inResourcePath)

Here you can find the source of isLegalFilePath(File inBasePath, File inResourcePath)

Description

check if the resource path is a subpath of the basepath

License

Open Source License

Parameter

Parameter Description
inBasePath a parameter
inResourcePath a parameter

Declaration

public static boolean isLegalFilePath(File inBasePath, File inResourcePath) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.IOException;

public class Main {
    /**//w ww.  ja  va2 s  . com
     * check if the resource path is a subpath of the basepath
     * @param inBasePath
     * @param inResourcePath
     * @return
     */
    public static boolean isLegalFilePath(File inBasePath, File inResourcePath) {

        try {

            return inResourcePath.getCanonicalPath().startsWith(inBasePath.getCanonicalPath());

        } catch (final Exception e) {

            return false;
        }
    }

    /**
     * NPE safe {@link String} startsWith
     * 
     * @param inStart
     * @param inValue
     * @return
     */
    public static boolean startsWith(String inStart, String inValue) {

        if (inStart == null && inValue == null) {

            return true;

        } else if (inStart == null || inValue == null) {

            return false;
        }

        return inValue.startsWith(inStart);
    }

    public static String getCanonicalPath(File inFile, boolean inThrowRuntimeException) {

        try {
            return inFile.getCanonicalPath();
        } catch (final IOException e) {

            if (inThrowRuntimeException) {
                throw new RuntimeException(inFile == null ? "File is null" : e.getMessage(), e);
            }

            return null;
        }
    }
}

Related

  1. isLegalDir(final String dirname)
  2. isLegalFile(String filePath)