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:edu.ku.brc.util.AttachmentUtils.java

/**
 * @param attachmentLocation/* www  .ja  v  a 2  s  .c  o  m*/
 * @return
 */
public static boolean isAttachmentDirMounted(final File attachmentLocation) {
    String fullPath = "";
    String statsMsg = "The test to write to the AttachmentLocation [%s] %s.";
    try {
        fullPath = attachmentLocation.getCanonicalPath();

        if (attachmentLocation.exists()) {
            if (attachmentLocation.isDirectory()) {
                File tmpFile = new File(attachmentLocation.getAbsoluteFile() + File.separator
                        + System.currentTimeMillis() + System.getProperty("user.name"));
                //log.debug(String.format("Trying to write a file to AttachmentLocation [%s]", tmpFile.getCanonicalPath()));
                if (tmpFile.createNewFile()) {
                    // I don't think I need this anymore
                    FileOutputStream fos = FileUtils.openOutputStream(tmpFile);
                    fos.write(1);
                    fos.close();
                    tmpFile.delete();

                    //log.debug(String.format(statsMsg, fullPath, "succeeded"));

                    return true;

                } else {
                    log.error(String.format("The Attachment Location [%s] atachment file couldn't be created",
                            fullPath));
                }
            } else {
                log.error(String.format("The Attachment Location [%s] is not a directory.", fullPath));
            }
        } else {
            log.error(String.format("The Attachment Location [%s] doesn't exist.", fullPath));
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    log.debug(String.format(statsMsg, fullPath, "failed"));

    return false;
}

From source file:com.ikon.module.db.stuff.FsDataStore.java

/**
 * Purge orphan datastore files helper/* ww w  . jav a  2 s.co  m*/
 */
private static void purgeOrphanFilesHelper(Session session, File dir) throws HibernateException, IOException {
    for (File child : dir.listFiles()) {
        if (child.isFile()) {
            if (session.get(NodeDocumentVersion.class, child.getName()) == null) {
                if (!child.delete()) {
                    log.warn("Could not delete file '" + child.getCanonicalPath() + "'");
                }
            }
        } else if (child.isDirectory()) {
            purgeOrphanFilesHelper(session, child);
        }
    }
}

From source file:apim.restful.importexport.utils.ArchiveGeneratorUtil.java

/**
 * Add files of the directory to the archive
 *
 * @param directoryToZip  Location of the archive
 * @param file            File to be included in the archive
 * @param zipOutputStream Output stream// ww w.  ja v a 2  s.c o m
 * @throws APIExportException If an error occurs while writing files to the archive
 */
private static void addToArchive(File directoryToZip, File file, ZipOutputStream zipOutputStream)
        throws APIExportException {

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(file);

        // Get relative path from archive directory to the specific file
        String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
                file.getCanonicalPath().length());
        if (File.separatorChar != '/')
            zipFilePath = zipFilePath.replace(File.separatorChar,
                    APIImportExportConstants.ARCHIVE_PATH_SEPARATOR);
        ZipEntry zipEntry = new ZipEntry(zipFilePath);
        zipOutputStream.putNextEntry(zipEntry);

        IOUtils.copy(fileInputStream, zipOutputStream);

        zipOutputStream.closeEntry();
    } catch (IOException e) {
        log.error("I/O error while writing files to archive" + e.getMessage());
        throw new APIExportException("I/O error while writing files to archive", e);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:net.certiv.antlr.project.util.Utils.java

/**
 * Move all files from the source directory to the destination directory.
 * //from w  w  w  .  j ava  2  s . c om
 * @param source
 *            the source directory
 * @param dest
 *            the destination directory
 * @return
 * @throws IOException
 */
public static boolean moveAllFiles(File source, File dest) throws IOException {
    if (source == null || dest == null)
        throw new IllegalArgumentException("Directory cannot be null");
    if (!source.exists() || !source.isDirectory())
        throw new IOException("Source directory must exist: " + source.getCanonicalPath());

    dest.mkdirs();
    if (!dest.exists() || !dest.isDirectory())
        throw new IOException("Destination directory must exist: " + dest.getCanonicalPath());

    Path srcDir = source.toPath();
    Path dstDir = dest.toPath();
    DirectoryStream<Path> ds = Files.newDirectoryStream(srcDir);
    int tot = 0;
    for (Path src : ds) {
        Files.copy(src, dstDir.resolve(src.getFileName()), REPLACE_EXISTING);
        tot++;
    }
    Log.info(Utils.class, "Moved " + tot + " files");
    return false;
}

From source file:com.limegroup.gnutella.util.Launcher.java

/**
 * Launches the Explorer/Finder and highlights the file.
 * //from w w w  . j a v  a  2  s .  co  m
 * @param file the file to show in explorer
 * @return null, if not supported by platform; the launched process otherwise
 * @see #launchFile(File)
 */
public static void launchExplorer(File file) throws IOException, SecurityException {
    if (OSUtils.isWindows()) {
        String explorePath = file.getPath();
        try {
            explorePath = file.getCanonicalPath();
        } catch (IOException ignored) {
        }

        if (file.isDirectory()) {
            // launches explorer in the directory
            LimeProcess.exec(new String[] { "explorer", explorePath });
        } else {
            // launches explorer and highlights the file
            LimeProcess.exec(new String[] { "explorer", "/select,", explorePath });
        }

    } else if (OSUtils.isMacOSX()) {
        // launches the Finder and highlights the file
        LimeProcess.exec(selectFileCommand(file));
    } else if (OSUtils.isLinux()) {
        if (file.isDirectory()) {
            Desktop.getDesktop().open(file);
        } else if (file.isFile()) {
            Desktop.getDesktop().open(file.getParentFile());
        }
    }
}

From source file:net.andydvorak.intellij.lessc.fs.LessFile.java

/**
 * Similar to {@link #getCanonicalPath()}, but falls back to returning {@link #getAbsolutePath()} instead of throwing an {@link IOException}.
 * @return the canonical path to the {@code File} if it exists; otherwise the absolute path
 *///  ww  w.j  a va  2 s .  c  o m
private static String getCanonicalPathSafe(final File file) {
    try {
        return file.getCanonicalPath();
    } catch (IOException ignored) {
        return file.getAbsolutePath();
    }
}

From source file:com.zotoh.core.util.FileUte.java

/**
 * @param srcFile/*  ww  w.  jav  a  2s.c om*/
 * @param destFile
 * @throws IOException
 */
public static void copyFile(File srcFile, File destFile) throws IOException {
    tstObjArg("source-file", srcFile);
    tstObjArg("dest-file", destFile);

    if (srcFile == destFile || srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
        return;
    }

    if (!srcFile.exists() || !srcFile.isFile()) {
        throw new IOException("\"" + srcFile + "\" does not exist or not a valid file");
    }

    if (!new File(destFile.getParent()).mkdirs()) {
        throw new IOException("Failed to create directory for \"" + destFile + "\"");
    }

    copyOneFile(srcFile, destFile);
}

From source file:com.izforge.izpack.util.IoHelper.java

/**
 * Creates a temp file with delete on exit rule. The extension is extracted from the template if
 * possible, else the default extension is used. The contents of template will be copied into
 * the temporary file.//w  w w  .  j a  va2  s. c o m
 *
 * @param templateFile         file to copy from and define file extension
 * @param defaultExtension file extension if no is contained in template
 * @return newly created and filled temporary file
 * @throws IOException if an I/O error occurred
 */
public static File copyToTempFile(File templateFile, String defaultExtension) throws IOException {
    String path = templateFile.getCanonicalPath();
    int pos = path.lastIndexOf('.');
    String ext = path.substring(pos);
    if (ext.isEmpty()) {
        ext = defaultExtension;
    }
    File tmpFile = File.createTempFile("izpack_io", ext);
    tmpFile.deleteOnExit();
    FileUtils.copyFile(templateFile, tmpFile);
    return tmpFile;
}

From source file:gpms.utils.PolicyTestUtil.java

/**
 * This creates the expected XACML response from a file
 *
 * @param rootDirectory/*  w  w  w . j a  v a2 s. co m*/
 *            root directory of the response files
 * @param versionDirectory
 *            version directory of the response files
 * @param responseId
 *            response file name
 * @return ResponseCtx or null if any error
 */
public static ResponseCtx createResponse(String rootDirectory, String versionDirectory, String responseId) {

    File file = new File(".");
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.RESPONSE_DIRECTORY + File.separator + responseId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        return ResponseCtx.getInstance(doc.getDocumentElement());
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        // ignore any exception and return null
    }

    return null;
}

From source file:FileHelper.java

public static boolean areInSync(File source, File destination) throws IOException {
    if (source.isDirectory()) {
        if (!destination.exists()) {
            return false;
        } else if (!destination.isDirectory()) {
            throw new IOException("Source and Destination not of the same type:" + source.getCanonicalPath()
                    + " , " + destination.getCanonicalPath());
        }/*from w  w  w .  j a v a 2 s. co  m*/
        String[] sources = source.list();
        Set<String> srcNames = new HashSet<String>(Arrays.asList(sources));
        String[] dests = destination.list();

        // check for files in destination and not in source
        for (String fileName : dests) {
            if (!srcNames.contains(fileName)) {
                return false;
            }
        }

        boolean inSync = true;
        for (String fileName : sources) {
            File srcFile = new File(source, fileName);
            File destFile = new File(destination, fileName);
            if (!areInSync(srcFile, destFile)) {
                inSync = false;
                break;
            }
        }
        return inSync;
    } else {
        if (destination.exists() && destination.isFile()) {
            long sts = source.lastModified() / FAT_PRECISION;
            long dts = destination.lastModified() / FAT_PRECISION;
            return sts == dts;
        } else {
            return false;
        }
    }
}