Example usage for java.io File getCanonicalPath

List of usage examples for java.io File getCanonicalPath

Introduction

In this page you can find the example usage for java.io File getCanonicalPath.

Prototype

public String getCanonicalPath() throws IOException 

Source Link

Document

Returns the canonical pathname string of this abstract pathname.

Usage

From source file:com.google.dart.tools.core.utilities.io.FileUtilities.java

/**
 * If the file with given path exists, and its canonical path differs from the given path only in
 * case, return the path with the same case as the {@link File} in the file system.
 * <p>/*from ww  w  . j a v  a  2  s  . com*/
 * According to specification it is OK to use a different case in URI, as long as embedding allows
 * this. But Eclipse LTK (refactoring framework) is not happy. We need to convert such URI to
 * canonical, at least during refactoring.
 */
public static String getFileSystemCase(String path) {
    File file = new File(path);
    if (file.exists()) {
        try {
            String absolutePath = file.getAbsolutePath();
            String canonicalPath = file.getCanonicalPath();
            if (StringUtils.equalsIgnoreCase(absolutePath, canonicalPath)) {
                return canonicalPath;
            }
        } catch (Throwable e) {
        }
    }
    return path;
}

From source file:com.google.dart.java2dart.engine.MainAnalysisServer.java

/**
 * @param serverPackage the sub-package in <code>com/google/dart/server</code>.
 * @return <code>true</code> if given {@link File} is located in sub-package of Engine project.
 *//*w  w w  . j  a  v a  2s.  co  m*/
private static boolean isServerPath(File file, String serverPackage) throws Exception {
    String filePath = file.getCanonicalPath();
    String prefix = serverFolder.getCanonicalPath() + "/com/google/dart/server/" + serverPackage;
    return filePath.startsWith(prefix);
}

From source file:com.google.dart.java2dart.engine.MainAnalysisServer.java

/**
 * @param servicePackage the sub-package in <code>com/google/dart/engine/services</code>.
 * @return <code>true</code> if given {@link File} is located in sub-package of Engine project.
 */// ww  w  .  j a  va  2  s.  c o  m
private static boolean isServicePath(File file, String servicePackage) throws Exception {
    String filePath = file.getCanonicalPath();
    String prefix = serviceFolder.getCanonicalPath() + "/com/google/dart/engine/services/" + servicePackage;
    return filePath.startsWith(prefix);
}

From source file:com.tesora.dve.common.PEFileUtils.java

/**
 * Write the text out to the specified filename.
 * /*from   w  w  w.  ja  va  2  s .  c  o m*/
 * @param fileName
 * @param text
 * @param overwriteContents
 * @throws Exception
 */
public static void writeToFile(File file, String text, boolean overwriteContents) throws PEException {
    BufferedWriter bw = null;
    try {
        if (file.exists() && !overwriteContents)
            throw new PEException("File '" + file.getCanonicalPath() + "' already exists");

        createDirectory(file.getParent());

        bw = new BufferedWriter(new FileWriter(file));
        bw.write(text);
    } catch (Exception e) {
        throw new PEException("Failed to write to file", e);
    } finally {
        if (bw != null) {
            try {
                bw.close();
            } catch (Exception e) {
                // Eat it
            }
        }
    }
}

From source file:eu.annocultor.common.Utils.java

static public byte[] readResourceFile(File src) throws IOException {
    if (src == null)
        throw new NullPointerException("Null src");
    String srcPath;//  w w  w .j ava2s  .  c  om
    try {
        srcPath = src.getCanonicalPath();
    } catch (Exception e) {
        throw new IOException(e.getMessage() + " on " + src.getName());
    }
    if (srcPath.contains("!")) {
        // JARs
        // remove dire prefix
        if (srcPath.indexOf("file:") != srcPath.lastIndexOf("file:"))
            throw new IOException("Source " + srcPath + " should contain only one substring 'file:'");

        srcPath = srcPath.substring(srcPath.indexOf("file:") + "file:".length());
        String[] srcPaths = srcPath.split("!");
        if (srcPaths.length != 2)
            throw new IOException(
                    "Source " + srcPath + " should contain no '!' for plain files or just '!' for jar files.");

        if (srcPaths[1].startsWith("/") || srcPaths[1].startsWith("\\"))
            srcPaths[1] = srcPaths[1].substring(1);

        JarResources jr = new JarResources(srcPaths[0]);
        byte[] buf = jr.getResource(srcPaths[1]);

        if (buf == null)
            throw new NullPointerException("Null resource: " + srcPaths[1] + " from " + srcPaths[0]);
        return buf;
    } else {
        // plain files
        return getBytesFromFile(src);
    }
}

From source file:net.sf.sahi.util.Utils.java

public static String getAbsolutePath(File file) {
    String path = "";
    try {//  ww w.  j a  v  a2 s .c  o  m
        path = file.getCanonicalPath();
    } catch (IOException e) {
        path = file.getAbsolutePath();
    }
    return path;
}

From source file:com.cisco.dvbu.ps.common.scriptutil.ScriptUtil.java

/**
 * Create the Composite Studio Enable VCS property file.  The property file name is of the format <composite_user>.<domain>.<composite_server_host>.properties.
 * @param vcsIncludeResourceSecurity - the value is either "true" or "false"
 * @param vcsWorkspacePathOverride - this is a way of overriding the vcs workspace path.  The vcsWorkspacePath is derived from the studio.properties file properties:
 *                                   VCS_WORKSPACE_DIR+"/"+VCS_PROJECT_ROOT.  It will use the substitute drive by default.
 * @param vcsScriptBinFolderOverride - this is the bin folder name only for PDTool Studio.  Since PDTool Studio can now support multiple hosts via multiple /bin folders,
 *                             it is optional to pass in the /bin folder location.  e.g. bin_host1, bin_host2.  The default will be bin if the input is null or blank.                                 
 * @param studioPropertyName - the name of the PDTool configuration property file.  The default is studio.properties
 * @param PDToolHomeDir - the directory of the PDToolStudio home directory
 * @param propertyFilePath - this is the full path to the output file.  For windows 7 the location will be in %USERPROFILE%\.compositesw
 * /* w  ww  . java  2 s.c  o m*/
 * usage createStudioEnableVCSPropertyFile true studio.properties D/:/CompositeSoftware/CIS6.2.0/conf/studio/PDToolStudio62 C:/Users/mike/.compositesw/admin.composite.localhost.properties
 */
public static void createStudioEnableVCSPropertyFile(String vcsIncludeResourceSecurity,
        String vcsWorkspacePathOverride, String vcsScriptBinFolderOverride, String studioPropertyName,
        String PDToolHomeDir, String propertyFilePath) {

    String prefix = "createStudioEnableVCSPropertyFile";
    // Set the global suppress and debug properties used throughout this class
    String validOptions = "true,false";
    // Get the property from the property file
    String debug = CommonUtils.getFileOrSystemPropertyValue(studioPropertyName, "DEBUG1");
    boolean debug1 = false;
    if (debug != null && validOptions.contains(debug)) {
        debug1 = Boolean.valueOf(debug);
    }

    if (!vcsIncludeResourceSecurity.equals("true") && !vcsIncludeResourceSecurity.equals("false")) {
        throw new ApplicationException(
                "The variable vcsIncludeResourceSecurity may only be set to \"true\" or \"false\"");
    }
    if (vcsWorkspacePathOverride != null)
        vcsWorkspacePathOverride = vcsWorkspacePathOverride.trim();

    if (vcsScriptBinFolderOverride != null)
        vcsScriptBinFolderOverride = vcsScriptBinFolderOverride.trim();

    CommonUtils.writeOutput("", prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("--- INPUT PARAMETERS ----", prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("", prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("    vcsIncludeResourceSecurity=" + vcsIncludeResourceSecurity, prefix, "-debug1",
            logger, debug1, false, false);
    CommonUtils.writeOutput("    vcsWorkspacePathOverride=[" + vcsWorkspacePathOverride + "]  len="
            + vcsWorkspacePathOverride.length(), prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("    vcsScriptFolderOverride=[" + vcsScriptBinFolderOverride + "]  len="
            + vcsScriptBinFolderOverride.length(), prefix, "-debug1", logger, debug1, false, false);
    CommonUtils.writeOutput("    studioPropertyName=" + studioPropertyName, prefix, "-debug1", logger, debug1,
            false, false);
    CommonUtils.writeOutput("    PDToolHomeDir=" + PDToolHomeDir, prefix, "-debug1", logger, debug1, false,
            false);
    CommonUtils.writeOutput("    propertyFilePath=" + propertyFilePath, prefix, "-debug1", logger, debug1,
            false, false);
    CommonUtils.writeOutput("", prefix, "-debug1", logger, debug1, false, false);

    StringBuffer sb = new StringBuffer();
    try {
        Format formatter;
        Date date = new Date();
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String dt = formatter.format(date);

        String VCS_WORKSPACE_DIR = CommonUtils.extractVariable("",
                CommonUtils.getFileOrSystemPropertyValue(studioPropertyName, "VCS_WORKSPACE_DIR"),
                "studio.properties", true);
        File absFile = new File(VCS_WORKSPACE_DIR);
        String VCS_WORKSPACE_DIR_ABS = CommonUtils.setCanonicalPath(absFile.getCanonicalPath());

        String VCS_PROJECT_ROOT = CommonUtils.extractVariable("",
                CommonUtils.getFileOrSystemPropertyValue(studioPropertyName, "VCS_PROJECT_ROOT"),
                "studio.properties", true);

        // Set the workspace path to the workspace override
        String vcsWorkspacePath = vcsWorkspacePathOverride;

        // If the vcs workspace path override is null then derive the path from the studio.properties.
        if (vcsWorkspacePath == null || vcsWorkspacePath.length() == 0) {
            vcsWorkspacePath = (VCS_WORKSPACE_DIR_ABS + "/" + VCS_PROJECT_ROOT);
            System.out.println("VCS_WORKSPACE_DIR=" + VCS_WORKSPACE_DIR_ABS);
            System.out.println("VCS_PROJECT_ROOT=" + VCS_PROJECT_ROOT);
            System.out.println("vcsWorkspacePath=[" + vcsWorkspacePath + "]");
        }

        CommonUtils.writeOutput("--- INTERNAL WORKING PARAMETERS ----", prefix, "-debug1", logger, debug1,
                false, false);
        CommonUtils.writeOutput("", prefix, "-debug1", logger, debug1, false, false);
        CommonUtils.writeOutput("VCS_WORKSPACE_DIR=" + VCS_WORKSPACE_DIR_ABS, prefix, "-debug1", logger, debug1,
                false, false);
        CommonUtils.writeOutput("VCS_PROJECT_ROOT=" + VCS_PROJECT_ROOT, prefix, "-debug1", logger, debug1,
                false, false);
        CommonUtils.writeOutput("pre-mod: vcsWorkspacePath=[" + vcsWorkspacePath + "]", prefix, "-debug1",
                logger, debug1, false, false);

        // Change all backslash to forward slashes to normalize the path
        vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement("\\\\"),
                Matcher.quoteReplacement("/"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        // Change all backslash to forward slashes to normalize the path
        vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement("\\"),
                Matcher.quoteReplacement("/"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        // Create a double backslash for paths
        vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement("/"),
                Matcher.quoteReplacement("\\\\"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        // Add \ in front of the C: so it will be C\:
        if (!vcsWorkspacePath.contains("\\:"))
            vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement(":"),
                    Matcher.quoteReplacement("\\:"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        // Change C\\: to C\:
        if (vcsWorkspacePath.contains("\\\\:"))
            vcsWorkspacePath = vcsWorkspacePath.replaceAll(Matcher.quoteReplacement("\\\\:"),
                    Matcher.quoteReplacement("\\:"));
        //         System.out.println("vcsWorkspacePath="+vcsWorkspacePath);

        //         System.out.println("vcsWorkspacePath=["+vcsWorkspacePath+"]");
        CommonUtils.writeOutput("post-mod: vcsWorkspacePath=[" + vcsWorkspacePath + "]", prefix, "-debug1",
                logger, debug1, false, false);

        // If the vcs script bin folder name override is null then derive the path from the default /bin location.
        String vcsScriptFolder = (PDToolHomeDir + "/bin");
        if (vcsScriptBinFolderOverride != null && vcsScriptBinFolderOverride.length() > 0)
            vcsScriptFolder = (PDToolHomeDir + "/" + vcsScriptBinFolderOverride);

        CommonUtils.writeOutput("pre-mod: vcsScriptFolder=[" + vcsScriptFolder + "]", prefix, "-debug1", logger,
                debug1, false, false);
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        // Change all backslash to forward slashes to normalize the path
        vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement("\\\\"),
                Matcher.quoteReplacement("/"));
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        // Change all backslash to forward slashes to normalize the path
        vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement("\\"),
                Matcher.quoteReplacement("/"));
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        // Create a double backslash for paths
        vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement("/"),
                Matcher.quoteReplacement("\\\\"));

        // Add \ in front of the C: so it will be C\:
        if (!vcsScriptFolder.contains("\\:"))
            vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement(":"),
                    Matcher.quoteReplacement("\\:"));
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        // Change C\\: to C\:
        if (vcsScriptFolder.contains("\\\\:"))
            vcsScriptFolder = vcsScriptFolder.replaceAll(Matcher.quoteReplacement("\\\\:"),
                    Matcher.quoteReplacement("\\:"));
        //         System.out.println("vcsScriptFolder="+vcsScriptFolder);

        //         System.out.println("vcsScriptFolder=["+vcsScriptFolder+"]");
        CommonUtils.writeOutput("post-mod: vcsScriptFolder=[" + vcsScriptFolder + "]", prefix, "-debug1",
                logger, debug1, false, false);

        sb.append("# Generated by ExecutePDToolStudio.bat\n");
        sb.append("# " + dt + "\n");
        sb.append("vcsIncludeResourceSecurity=" + vcsIncludeResourceSecurity + "\n");
        sb.append("vcsScriptFolder=" + vcsScriptFolder + "\n");
        sb.append("vcsWorkspacePath=" + vcsWorkspacePath + "\n");
        sb.append("enableVCS=true" + "\n");
    } catch (Exception e) {
        throw new ValidationException(e.getMessage(), e);
    }

    try {
        Writer out = new OutputStreamWriter(new FileOutputStream(propertyFilePath));
        out.write(sb.toString());
        out.flush();

        String fileContents = CommonUtils.getFileAsString(propertyFilePath);
        System.out.println("");
        System.out.println("");
        System.out.println(
                "-----------------------------------------------------------------------------------------------------");
        System.out.println("Property File Contents For [" + propertyFilePath + "]");
        System.out.println(
                "-----------------------------------------------------------------------------------------------------");
        System.out.println(fileContents);
        System.out.println("");
        CommonUtils.writeOutput("Property File Contents For [" + propertyFilePath + "]", prefix, "-debug1",
                logger, debug1, false, false);
        CommonUtils.writeOutput(fileContents, prefix, "-debug1", logger, debug1, false, false);

    } catch (FileNotFoundException e) {
        logger.error("Could not wirte to property file " + propertyFilePath, e);
        throw new ValidationException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Could not wirte to property file " + propertyFilePath, e);
        throw new ValidationException(e.getMessage(), e);
    }
}

From source file:graphene.util.fs.FileUtils.java

public static void deleteRecursively(final File directory) throws IOException {
        final Stack<File> stack = new Stack<>();
        final List<File> temp = new LinkedList<>();
        stack.push(directory.getAbsoluteFile());
        while (!stack.isEmpty()) {
            final File top = stack.pop();
            File[] files = top.listFiles();
            if (files != null) {
                for (final File child : files) {
                    if (child.isFile()) {
                        if (!deleteFile(child)) {
                            throw new IOException("Failed to delete " + child.getCanonicalPath());
                        }// w  w w  . ja v a 2 s . co  m
                    } else {
                        temp.add(child);
                    }
                }
            }
            files = top.listFiles();
            if ((files == null) || (files.length == 0)) {
                if (!deleteFile(top)) {
                    throw new IOException("Failed to delete " + top.getCanonicalPath());
                }
            } else {
                stack.push(top);
                for (final File f : temp) {
                    stack.push(f);
                }
            }
            temp.clear();
        }
    }

From source file:eu.annocultor.common.Utils.java

public static List<File> expandFileTemplateFrom(File dir, String... pattern) throws IOException {
    List<File> files = new ArrayList<File>();

    for (String p : pattern) {
        File fdir = new File(new File(dir, FilenameUtils.getFullPathNoEndSeparator(p)).getCanonicalPath());
        if (!fdir.isDirectory())
            throw new IOException("Error: " + fdir.getCanonicalPath() + ", expanded from directory "
                    + dir.getCanonicalPath() + " and pattern " + p + " does not denote a directory");
        if (!fdir.canRead())
            throw new IOException("Error: " + fdir.getCanonicalPath() + " is not readable");
        FileFilter fileFilter = new WildcardFileFilter(FilenameUtils.getName(p));
        File[] list = fdir.listFiles(fileFilter);
        if (list == null)
            throw new IOException("Error: " + fdir.getCanonicalPath()
                    + " does not denote a directory or something else is wrong");
        if (list.length == 0)
            throw new IOException("Error: no files found, template " + p + " from dir " + dir.getCanonicalPath()
                    + " where we recognised " + fdir.getCanonicalPath() + " as path and " + fileFilter
                    + " as file mask");
        for (File file : list) {
            if (!file.exists()) {
                throw new FileNotFoundException(
                        "File not found: " + file + " resolved to " + file.getCanonicalPath());
            }//from  w  ww.j a  v a 2s. c o  m
        }
        files.addAll(Arrays.asList(list));
    }

    return files;
}

From source file:com.github.fritaly.dualcommander.DirectoryBrowser.java

private static String getCanonicalPath(File file) {
    try {/*  w ww. java 2s.  c o  m*/
        return file.getCanonicalPath();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}