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:net.minecraftforge.fml.relauncher.CoreModManager.java

private static Map<String, File> extractContainedDepJars(JarFile jar, File baseModsDir, File versionedModsDir)
        throws IOException {
    Map<String, File> result = Maps.newHashMap();
    if (!jar.getManifest().getMainAttributes().containsKey(MODCONTAINSDEPS))
        return result;

    String deps = jar.getManifest().getMainAttributes().getValue(MODCONTAINSDEPS);
    String[] depList = deps.split(" ");
    for (String dep : depList) {
        String depEndName = new File(dep).getName(); // extract last part of name
        if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) {
            FMLRelaunchLog.log(Level.ERROR, "Skipping dep at request: %s", dep);
            continue;
        }//ww w .ja va  2  s .c om
        final JarEntry jarEntry = jar.getJarEntry(dep);
        if (jarEntry == null) {
            FMLRelaunchLog.log(Level.ERROR, "Found invalid ContainsDeps declaration %s in %s", dep,
                    jar.getName());
            continue;
        }
        File target = new File(versionedModsDir, depEndName);
        File modTarget = new File(baseModsDir, depEndName);
        if (target.exists()) {
            FMLRelaunchLog.log(Level.DEBUG, "Found existing ContainsDep extracted to %s, skipping extraction",
                    target.getCanonicalPath());
            result.put(dep, target);
            continue;
        } else if (modTarget.exists()) {
            FMLRelaunchLog.log(Level.DEBUG,
                    "Found ContainsDep in main mods directory at %s, skipping extraction",
                    modTarget.getCanonicalPath());
            result.put(dep, modTarget);
            continue;
        }

        FMLRelaunchLog.log(Level.DEBUG, "Extracting ContainedDep %s from %s to %s", dep, jar.getName(),
                target.getCanonicalPath());
        try {
            Files.createParentDirs(target);
            FileOutputStream targetOutputStream = null;
            InputStream jarInputStream = null;
            try {
                targetOutputStream = new FileOutputStream(target);
                jarInputStream = jar.getInputStream(jarEntry);
                ByteStreams.copy(jarInputStream, targetOutputStream);
            } finally {
                IOUtils.closeQuietly(targetOutputStream);
                IOUtils.closeQuietly(jarInputStream);
            }
            FMLRelaunchLog.log(Level.DEBUG, "Extracted ContainedDep %s from %s to %s", dep, jar.getName(),
                    target.getCanonicalPath());
            result.put(dep, target);
        } catch (IOException e) {
            FMLRelaunchLog.log(Level.ERROR, e, "An error occurred extracting dependency");
        }
    }
    return result;
}

From source file:de.huberlin.wbi.hiway.am.galaxy.GalaxyApplicationMaster.java

/**
 * A helper function for processing the loc file of a single Galaxy data table; the loc file stores information on any registered data (e.g., genomic
 * indices)//  w ww .j  a v  a 2  s.c  o m
 * 
 * @param file
 *            a data table's loc file
 * @param galaxyDataTable
 *            the data table object corresponding to this loc file
 */
private static void processLocFile(File file, GalaxyDataTable galaxyDataTable) {
    if (!file.exists())
        return;
    try (BufferedReader locBr = new BufferedReader(new FileReader(file))) {
        System.out.println("Processing Galaxy data table loc file " + file.getCanonicalPath());
        String line;
        while ((line = locBr.readLine()) != null) {
            if (line.startsWith(galaxyDataTable.getComment_char()))
                continue;
            String[] content = line.split("\t");
            galaxyDataTable.addContent(content);
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

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

public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)
        throws IOException {
    if (srcDir == null) {
        throw new NullPointerException("Source must not be null");
    }//from  w w w  .ja v  a 2 s.  c  om
    if (destDir == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (srcDir.exists() == false) {
        throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
    }
    if (srcDir.isDirectory() == false) {
        throw new IOException("Source '" + srcDir + "' exists but is not a directory");
    }
    if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
        throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
    }

    // Cater for destination being directory within the source directory (see IO-141)
    List<String> exclusionList = null;
    if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
        File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
        if (srcFiles != null && srcFiles.length > 0) {
            exclusionList = new ArrayList<String>(srcFiles.length);
            for (File srcFile : srcFiles) {
                File copiedFile = new File(destDir, srcFile.getName());
                exclusionList.add(copiedFile.getCanonicalPath());
            }
        }
    }
    doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);
}

From source file:maspack.fileutil.SafeFileUtils.java

/**
 * Copies a file to a new location.// w w w.j  ava2  s .  c  o m
 * <p>
 * This method copies the contents of the specified source file to the
 * specified destination file. The directory holding the destination file is
 * created if it does not exist. If the destination file exists, then this
 * method will overwrite it.
 * <p>
 * <strong>Note:</strong> Setting <code>preserveFileDate</code> to
 * {@code true} tries to preserve the file's last modified date/times using
 * {@link File#setLastModified(long)}, however it is not guaranteed that the
 * operation will succeed. If the modification operation fails, no indication
 * is provided.
 *
 * @param srcFile
 * an existing file to copy, must not be {@code null}
 * @param destFile
 * the new file, must not be {@code null}
 * @param options
 * determine whether to use file locks and preserve date information
 *
 * @throws NullPointerException
 * if source or destination is {@code null}
 * @throws IOException
 * if source or destination is invalid
 * @throws IOException
 * if an IO error occurs during copying
 */
public static void copyFile(File srcFile, File destFile, int options) throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }
    if (destFile == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (srcFile.exists() == false) {
        throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
    }
    if (srcFile.isDirectory()) {
        throw new IOException("Source '" + srcFile + "' exists but is a directory");
    }
    if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
        throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
    }
    File parentFile = destFile.getParentFile();
    if (parentFile != null) {
        if (!parentFile.mkdirs() && !parentFile.isDirectory()) {
            throw new IOException("Destination '" + parentFile + "' directory cannot be created");
        }
    }
    if (destFile.exists() && destFile.canWrite() == false) {
        throw new IOException("Destination '" + destFile + "' exists but is read-only");
    }
    doCopyFile(srcFile, destFile, options);
}

From source file:com.buaa.cfs.utils.Shell.java

/** fully qualify the path to a binary that should be in a known hadoop 
 *  bin location. This is primarily useful for disambiguating call-outs 
 *  to executable sub-components of Hadoop to avoid clashes with other 
 *  executables that may be in the path.  Caveat:  this call doesn't 
 *  just format the path to the bin directory.  It also checks for file 
 *  existence of the composed path. The output of this call should be 
 *  cached by callers./*from  ww  w  . ja v a2 s  .  c o m*/
 * */
public static final String getQualifiedBinPath(String executable) throws IOException {
    // construct hadoop bin path to the specified executable
    String fullExeName = HADOOP_HOME_DIR + File.separator + "bin" + File.separator + executable;

    File exeFile = new File(fullExeName);
    if (!exeFile.exists()) {
        throw new IOException("Could not locate executable " + fullExeName + " in the Hadoop binaries.");
    }

    return exeFile.getCanonicalPath();
}

From source file:net.redstonelamp.gui.RedstoneLampGUI.java

private static void addHistory(File file) {
    File config = new File("redstonelamp-gui-config.json");
    if (!config.isFile()) {
        try {/*w  ww.j a  va2  s. c  om*/
            InputStream is = RedstoneLampGUI.class.getResourceAsStream("redfstonelamp-gui-config.json");
            OutputStream os = new FileOutputStream(config);
            IOUtils.copy(is, os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        InputStream is = new FileInputStream(config);
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        is.close();
        try {
            JSONObject json = new JSONObject(new String(buffer));
            JSONArray array = json.getJSONArray("history");
            JSONObject object = new JSONObject();
            object.put("path", file.getCanonicalPath());
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.cedarsoft.io.LinkUtils.java

/**
 * Creates a link./*from   ww w  .  jav  a 2s  .  c  o  m*/
 * Returns true if the link has been created, false if the link (with the same link source) still exists.
 *
 * @param linkTarget the link source
 * @param linkFile   the link file
 * @param symbolic   whether to create a symbolic link
 * @return whether the link has been created (returns false if the link still existed)
 *
 * @throws IOException if something went wrong
 */
public static boolean createLink(@Nonnull File linkTarget, @Nonnull File linkFile, boolean symbolic)
        throws IOException {
    if (linkFile.exists()) {
        //Maybe the hard link still exists - we just don't know, so throw an exception
        if (!symbolic) {
            throw new IOException("link still exists " + linkFile.getAbsolutePath());
        }

        if (linkFile.getCanonicalFile().equals(linkTarget.getCanonicalFile())) {
            //still exists - that is ok, since it points to the same directory
            return false;
        } else {
            //Other target
            throw new IOException("A link still exists at <" + linkFile.getAbsolutePath()
                    + "> but with different target: <" + linkTarget.getCanonicalPath() + "> exected <"
                    + linkFile.getCanonicalPath() + ">");
        }
    }

    List<String> args = new ArrayList<String>();
    args.add("ln");
    if (symbolic) {
        args.add("-s");
    }
    args.add(linkTarget.getPath());
    args.add(linkFile.getAbsolutePath());

    ProcessBuilder builder = new ProcessBuilder(args);
    Process process = builder.start();
    try {
        int result = process.waitFor();
        if (result != 0) {
            throw new IOException("Creation of link failed: " + IOUtils.toString(process.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    return true;
}

From source file:edu.kit.dama.dataworkflow.util.DataWorkflowHelper.java

/**
 * Helper method to perform the actual substitution.
 *
 * @param pTask The task whose working directory should be checked for
 * substitution.// w  w  w .j ava  2 s . c  om
 * @param pTargetPath The target path.
 *
 * @throws IOException If the replacement operation fails for some reason.
 * @throws URISyntaxException If any of the URLs in the task (input, output,
 * temp or working dir URL) is invalid.
 */
private static void performSubstitution(DataWorkflowTask pTask, File pDirectory)
        throws IOException, URISyntaxException {
    File[] relevantFileList = pDirectory.listFiles(VAR_FILTER);
    LOGGER.info("Substituting variables in " + relevantFileList.length
            + ((relevantFileList.length == 1) ? " file" : " files"));

    for (File f : relevantFileList) {
        if (f.length() > 10 * FileUtils.ONE_MB) {
            LOGGER.warn(
                    "File {} has a size of {} bytes. Variable substitution is only supported for files with less than 10MB. File is skipped.",
                    f, f.length());
            continue;
        }
        //perform replacement
        LOGGER.info(" * Substituting variables in file '" + f.getPath() + "'");
        DataInputStream din = null;
        FileOutputStream fout = null;
        try {
            LOGGER.info("   - Reading input file");
            byte[] data = new byte[(int) f.length()];
            din = new DataInputStream(new FileInputStream(f));
            din.readFully(data);

            LOGGER.info("   - Substituting variables");
            String dataString = new String(data);

            String accessPointId = pTask.getExecutionEnvironment().getStagingAccessPointId();
            AbstractStagingAccessPoint accessPoint = StagingConfigurationManager.getSingleton()
                    .getAccessPointById(accessPointId);
            LOGGER.debug("  - Obtaining local path for input dir URL {}", pTask.getInputDirectoryUrl());
            File localPath = accessPoint.getLocalPathForUrl(new URL(pTask.getInputDirectoryUrl()),
                    getTaskContext(pTask));
            LOGGER.debug("  - Local path is: {}", localPath);
            String inputDirReplacement = localPath.getCanonicalPath();

            LOGGER.debug("  - Obtaining local path for output dir URL {}", pTask.getOutputDirectoryUrl());
            localPath = accessPoint.getLocalPathForUrl(new URL(pTask.getOutputDirectoryUrl()),
                    getTaskContext(pTask));
            String outputDirReplacement = localPath.getCanonicalPath();

            LOGGER.debug("  - Obtaining local path for working dir URL {}", pTask.getWorkingDirectoryUrl());
            localPath = accessPoint.getLocalPathForUrl(new URL(pTask.getWorkingDirectoryUrl()),
                    getTaskContext(pTask));
            String workingDirReplacement = localPath.getCanonicalPath();

            LOGGER.debug("  - Obtaining local path for temp dir URL {}", pTask.getTempDirectoryUrl());
            localPath = accessPoint.getLocalPathForUrl(new URL(pTask.getTempDirectoryUrl()),
                    getTaskContext(pTask));
            String tempDirReplacement = localPath.getCanonicalPath();

            LOGGER.info("     " + DATA_IN_DIR + ": " + inputDirReplacement);
            LOGGER.info("     " + DATA_OUT_DIR + ": " + outputDirReplacement);
            LOGGER.info("     " + TEMP_DIR + ": " + tempDirReplacement);
            LOGGER.info("     " + WORKING_DIR + ": " + workingDirReplacement);
            //replace all variables
            //To obtain a proper path format the input paths are put into a file object and the URI path is used for replacement. Therefore differences between
            //source and destination platform are not relevant. Due to the URI.toPath() returns the path with leading slash, we use the path beginning with
            //the second index to avoid problems with other programming languages not able to deal with the leading slash.
            dataString = dataString.replaceAll(Pattern.quote(DATA_IN_DIR_VARIABLE), inputDirReplacement)
                    .replaceAll(Pattern.quote(DATA_OUT_DIR_VARIABLE), outputDirReplacement)
                    .replaceAll(Pattern.quote(TEMP_DIR_VARIABLE), tempDirReplacement)
                    .replaceAll(Pattern.quote(WORKING_DIR_VARIABLE), workingDirReplacement);
            LOGGER.info("   - Writing output file");
            fout = new FileOutputStream(f);
            fout.write(dataString.getBytes());
            fout.flush();
            LOGGER.info(" * Substituting operations finished successfully");
        } finally {
            try {
                if (din != null) {
                    din.close();
                }
            } catch (IOException ioe) {
            }
            try {
                if (fout != null) {
                    fout.close();
                }
            } catch (IOException ioe) {
            }
        }
    }
    LOGGER.info("Directory {} processed successfully", pDirectory);
}

From source file:it.cnr.icar.eric.common.AbstractProperties.java

/**
 * Checks if a directory for the given name exists. If not, try to create it.
 *
 * @param homeDir A File descriptor for the directory to be checked.
 * @return Full path to the directory./*from w w w  .j ava2  s  . co  m*/
 * @throw JAXRException if it fails to find and create the directory.
 */
protected static String initHomeDir(String propName, File homeDir) {
    try {
        if (!homeDir.exists()) {
            if (!homeDir.mkdirs()) {
                throw new RuntimeException(CommonResourceBundle.getInstance()
                        .getString("message.createDirectory", new String[] { propName, homeDir.getPath() }));
            }
        } else {
            if (!homeDir.isDirectory()) {
                throw new RuntimeException(CommonResourceBundle.getInstance()
                        .getString("message.accessDirectory", new String[] { propName, homeDir.getPath() }));
            }
        }
        String homeDirStr = homeDir.getCanonicalPath();
        return homeDirStr;
    } catch (SecurityException se) {
        throw new RuntimeException(CommonResourceBundle.getInstance().getString("message.permissionDenied",
                new String[] { propName, homeDir.getPath(), se.toString() }));
    } catch (IOException io) {
        throw new RuntimeException(CommonResourceBundle.getInstance().getString("message.createAccessDirectory",
                new String[] { propName, homeDir.getPath(), io.toString() }));
    }
}

From source file:com.compomics.pladipus.core.control.util.ZipUtils.java

/**
 * Zips a single file to the specified folder
 *
 * @param input the original folder//from  w  w w  .  j a va 2s. c om
 * @param output the destination zip file
 */
public static void zipFile(File inputFile, File zipFile) {

    try (FileInputStream fileInputStream = new FileInputStream(inputFile);
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
        ZipEntry zipEntry = new ZipEntry(inputFile.getName());
        zipOutputStream.putNextEntry(zipEntry);
        byte[] buf = new byte[1024];
        int bytesRead;

        // Read the input file by chucks of 1024 bytes
        // and write the read bytes to the zip stream
        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zipOutputStream.write(buf, 0, bytesRead);
        }

        // close ZipEntry to store the stream to the file
        zipOutputStream.closeEntry();
        LOGGER.debug("Regular file :" + inputFile.getCanonicalPath() + " is zipped to archive :"
                + zipFile.getAbsolutePath());
    } catch (IOException e) {
        LOGGER.error(e);
    }

}