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.opengamma.examples.simulated.tool.ExampleDatabasePopulator.java

private static String unpackJar(URL resource) {
    String file = resource.getPath();
    if (file.contains(".jar!/")) {
        s_logger.info("Unpacking zip file located within a jar file: {}", resource);
        String jarFileName = StringUtils.substringBefore(file, "!/");
        if (jarFileName.startsWith("file:/")) {
            jarFileName = jarFileName.substring(5);
            if (SystemUtils.IS_OS_WINDOWS) {
                jarFileName = StringUtils.stripStart(jarFileName, "/");
            }/*w w w .ja  v a 2  s.c o  m*/
        } else if (jarFileName.startsWith("file:/")) {
            jarFileName = jarFileName.substring(6);
        }
        jarFileName = StringUtils.replace(jarFileName, "%20", " ");
        String innerFileName = StringUtils.substringAfter(file, "!/");
        innerFileName = StringUtils.replace(innerFileName, "%20", " ");
        s_logger.info("Unpacking zip file found jar file: {}", jarFileName);
        s_logger.info("Unpacking zip file found zip file: {}", innerFileName);
        try {
            JarFile jar = new JarFile(jarFileName);
            JarEntry jarEntry = jar.getJarEntry(innerFileName);
            try (InputStream in = jar.getInputStream(jarEntry)) {
                File tempFile = File.createTempFile("simulated-examples-database-populator-", ".zip");
                tempFile.deleteOnExit();
                try (OutputStream out = new FileOutputStream(tempFile)) {
                    IOUtils.copy(in, out);
                }
                file = tempFile.getCanonicalPath();
            }
        } catch (IOException ex) {
            throw new OpenGammaRuntimeException("Unable to open file within jar file: " + resource, ex);
        }
        s_logger.debug("Unpacking zip file extracted to: {}", file);
    }
    return file;
}

From source file:frameworks.Masken.java

public static void uncompressTarGZ(File tarFile, File dest) throws IOException {
    dest.mkdir();/*  w w  w.  j  a va  2 s. c o  m*/
    TarArchiveInputStream tarIn = null;

    tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tarFile))));

    TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
    // tarIn is a TarArchiveInputStream
    while (tarEntry != null) {// create a file with the same name as the tarEntry
        File destPath = new File(dest, tarEntry.getName());
        System.out.println("working: " + destPath.getCanonicalPath());
        if (tarEntry.isDirectory()) {
            destPath.mkdirs();
        } else {
            if (!destPath.getParentFile().exists()) {
                destPath.getParentFile().mkdirs();
            }
            destPath.createNewFile();
            //byte [] btoRead = new byte[(int)tarEntry.getSize()];
            byte[] btoRead = new byte[1024];
            //FileInputStream fin 
            //  = new FileInputStream(destPath.getCanonicalPath());
            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
            int len = 0;

            while ((len = tarIn.read(btoRead)) != -1) {
                bout.write(btoRead, 0, len);
            }

            bout.close();
            btoRead = null;

        }
        tarEntry = tarIn.getNextTarEntry();
    }
    tarIn.close();
}

From source file:net.sf.jabref.external.RegExpFileSearch.java

/**
 * Internal Version of findFile, which also accepts a current directory to
 * base the search on./*w w w .  j av  a  2s  . c  o  m*/
 *
 */
private static List<File> findFile(BibEntry entry, String directory, String file, String extensionRegExp) {

    File root;
    if (directory == null) {
        root = new File(".");
    } else {
        root = new File(directory);
    }
    if (!root.exists()) {
        return Collections.emptyList();
    }
    List<File> fileList = RegExpFileSearch.findFile(entry, root, file, extensionRegExp);

    List<File> result = new ArrayList<>();
    for (File tmpFile : fileList) {
        try {
            /**
             * [ 1601651 ] PDF subdirectory - missing first character
             *
             * http://sourceforge.net/tracker/index.php?func=detail&aid=1601651&group_id=92314&atid=600306
             */
            // Changed by M. Alver 2007.01.04:
            // Remove first character if it is a directory separator character:
            String tmp = tmpFile.getCanonicalPath().substring(root.getCanonicalPath().length());
            if ((tmp.length() > 1) && (tmp.charAt(0) == File.separatorChar)) {
                tmp = tmp.substring(1);
            }
            result.add(new File(tmp));

        } catch (IOException e) {
            LOGGER.warn("Problem searching", e);
        }
    }
    return result;
}

From source file:FileHelper.java

public static void synchronize(File source, File destination, boolean smart, long chunkSize)
        throws IOException {
    if (chunkSize <= 0) {
        System.out.println("Chunk size must be positive: using default value.");
        chunkSize = DEFAULT_COPY_BUFFER_SIZE;
    }//  www  .  j a v  a 2 s  . c o  m
    if (source.isDirectory()) {
        if (!destination.exists()) {
            if (!destination.mkdirs()) {
                throw new IOException("Could not create path " + destination);
            }
        } else if (!destination.isDirectory()) {
            throw new IOException("Source and Destination not of the same type:" + source.getCanonicalPath()
                    + " , " + destination.getCanonicalPath());
        }
        String[] sources = source.list();
        Set<String> srcNames = new HashSet<String>(Arrays.asList(sources));
        String[] dests = destination.list();

        //delete files not present in source
        for (String fileName : dests) {
            if (!srcNames.contains(fileName)) {
                delete(new File(destination, fileName));
            }
        }
        //copy each file from source
        for (String fileName : sources) {
            File srcFile = new File(source, fileName);
            File destFile = new File(destination, fileName);
            synchronize(srcFile, destFile, smart, chunkSize);
        }
    } else {
        if (destination.exists() && destination.isDirectory()) {
            delete(destination);
        }
        if (destination.exists()) {
            long sts = source.lastModified() / FAT_PRECISION;
            long dts = destination.lastModified() / FAT_PRECISION;
            //do not copy if smart and same timestamp and same length
            if (!smart || sts == 0 || sts != dts || source.length() != destination.length()) {
                copyFile(source, destination, chunkSize);
            }
        } else {
            copyFile(source, destination, chunkSize);
        }
    }
}

From source file:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset.// ww w. j  av  a2 s .  c om
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}

From source file:com.dvlcube.cuber.utils.FileUtils.java

public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }//from   w  w w  . j  a va2  s  .  c  o  m
    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");
    }
    if (destFile.getParentFile() != null && destFile.getParentFile().exists() == false) {
        if (destFile.getParentFile().mkdirs() == false) {
            throw new IOException("Destination '" + destFile + "' directory cannot be created");
        }
    }
    if (destFile.exists() && destFile.canWrite() == false) {
        throw new IOException("Destination '" + destFile + "' exists but is read-only");
    }
    doCopyFile(srcFile, destFile, preserveFileDate);
}

From source file:com.nary.io.FileUtils.java

/**
 * Given a directory and filename, combine them and return the full canonical path.
 *//*from w  w w  .j  a v  a2  s  . co m*/
public static String getCanonicalPath(String directory, String fileName) {
    File f = new File(directory, fileName);
    try {
        return f.getCanonicalPath();
    } catch (IOException e) {
        return f.getPath();
    }
}

From source file:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java

/**
 * Get the concurrent path if possible, otherwise get the absolute path.
 * //  w w  w . jav a 2  s.c o  m
 * @param file File
 * @return String path of file. Concurrent path if possible.
 */
private static String getRealPath(File file) {
    try {
        return file.getCanonicalPath();
    } catch (IOException ioe) {
        return file.getAbsolutePath();
    }
}

From source file:com.opendesign.utils.CmnUtil.java

/**
 * ?  database?  path/*from  w w  w . j a va 2  s .  c om*/
 * 
 * @param request
 * @param file
 * @return
 * @throws IOException
 */
public static String getFileUploadDbPath(HttpServletRequest request, File file) throws IOException {
    String realRootPath = request.getServletContext().getRealPath("/");
    String dbPath = file.getCanonicalPath().replace(realRootPath, "/");
    dbPath = dbPath.replaceAll("\\\\", "/");
    dbPath = dbPath.replaceAll("//", "/");
    return dbPath;
}

From source file:org.agiso.tempel.starter.Bootstrap.java

/**
 * @param cmd//from   w w  w . java  2 s . co m
 * @return
 * @throws IOException
 */
private static String determineWorkDir(CommandLine cmd) throws IOException {
    File workDir;
    if (cmd.hasOption('d')) {
        workDir = new File(cmd.getOptionValue('d').trim());
        if (!workDir.exists()) {
            starterLogger.error(Logs.LOG_04, ansiString(RED, workDir.getPath()));
            System.exit(-2);
        } else if (!workDir.isDirectory()) {
            starterLogger.error(Logs.LOG_05, ansiString(RED, workDir.getPath()));
            System.exit(-3);
        }
    } else {
        workDir = new File(".");
    }

    starterLogger.debug(Logs.LOG_03, ansiString(GREEN, workDir.getPath()));
    return workDir.getCanonicalPath();
}