/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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;
public class Main {
/**
* Return the path within a base directory
*/
public static String getContextFilePath(String directoryPath, String filePath) {
try {
File directory = new File(directoryPath);
File file = new File(filePath);
directoryPath = directory.getCanonicalPath();
filePath = file.getCanonicalPath();
// If the context directory does not have a File.separator
// at the end then add one explicitly
if(!directoryPath.endsWith(File.separator)){
directoryPath += File.separator;
}
// If the context dir contains both kinds of separator
// then standardize on using the File.separator
if ((directoryPath.indexOf('/') !=-1) && (directoryPath.indexOf('\\') !=-1)) {
directoryPath = directoryPath.replace('\\', File.separator.charAt(0));
directoryPath = directoryPath.replace('/', File.separator.charAt(0));
}
// If the file path contains both kinds of separator
// then standardize on using the File.separator
if ((filePath.indexOf('/') !=-1) && (filePath.indexOf('\\') !=-1)) {
filePath = filePath.replace('\\', File.separator.charAt(0));
filePath = filePath.replace('/', File.separator.charAt(0));
}
if (filePath.startsWith(directoryPath)) {
filePath = filePath.substring(directoryPath.length());
}
} catch (Exception e){
// ignore
}
return filePath;
}
}
|