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.l2jfree.gameserver.util.DatabaseBackupManager.java

public static void makeBackup() {
    File f = new File(Config.DATAPACK_ROOT, Config.DATABASE_BACKUP_SAVE_PATH);
    if (!f.mkdirs() && !f.exists()) {
        _log.warn("Could not create folder " + f.getAbsolutePath());
        return;/*from  www.j  av  a 2  s . c om*/
    }

    _log.info("DatabaseBackupManager: backing up `" + Config.DATABASE_BACKUP_DATABASE_NAME + "`...");

    Process run = null;
    try {
        run = Runtime.getRuntime().exec("mysqldump" + " --user=" + Config.DATABASE_LOGIN + " --password="
                + Config.DATABASE_PASSWORD
                + " --compact --complete-insert --default-character-set=utf8 --extended-insert --lock-tables --quick --skip-triggers "
                + Config.DATABASE_BACKUP_DATABASE_NAME, null, new File(Config.DATABASE_BACKUP_MYSQLDUMP_PATH));
    } catch (Exception e) {
    } finally {
        if (run == null) {
            _log.warn("Could not execute mysqldump!");
            return;
        }
    }

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        Date time = new Date();

        File bf = new File(f, sdf.format(time) + (Config.DATABASE_BACKUP_COMPRESSION ? ".zip" : ".sql"));
        if (!bf.createNewFile())
            throw new IOException("Cannot create backup file: " + bf.getCanonicalPath());
        InputStream input = run.getInputStream();
        OutputStream out = new FileOutputStream(bf);
        if (Config.DATABASE_BACKUP_COMPRESSION) {
            ZipOutputStream dflt = new ZipOutputStream(out);
            dflt.setMethod(ZipOutputStream.DEFLATED);
            dflt.setLevel(Deflater.BEST_COMPRESSION);
            dflt.setComment("L2JFree Schema Backup Utility\r\n\r\nBackup date: "
                    + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS z").format(time));
            dflt.putNextEntry(new ZipEntry(Config.DATABASE_BACKUP_DATABASE_NAME + ".sql"));
            out = dflt;
        }

        byte[] buf = new byte[4096];
        int written = 0;
        for (int read; (read = input.read(buf)) != -1;) {
            out.write(buf, 0, read);

            written += read;
        }
        input.close();
        out.close();

        if (written == 0) {
            bf.delete();
            BufferedReader br = new BufferedReader(new InputStreamReader(run.getErrorStream()));
            String line;
            while ((line = br.readLine()) != null)
                _log.warn("DatabaseBackupManager: " + line);
            br.close();
        } else
            _log.info("DatabaseBackupManager: Schema `" + Config.DATABASE_BACKUP_DATABASE_NAME
                    + "` backed up successfully in " + (System.currentTimeMillis() - time.getTime()) / 1000
                    + " s.");

        run.waitFor();
    } catch (Exception e) {
        _log.warn("DatabaseBackupManager: Could not make backup: ", e);
    }
}

From source file:com.bc.util.io.FileUtils.java

public static boolean isSymbolicLink(File file) throws IOException {
    if (file == null) {
        throw new IllegalArgumentException("File cannot be null");
    }/*from   w ww. j  a  v  a  2 s .  co  m*/

    //next line dereferences symbolic links along the path.
    //eg. if path is /tmp/somedir/linktosomewhere/filename
    // and /tmp/somedir/linktosomewhere is a link to /tmp/somedir2
    // then this file is now /tmp/somedir2/filename
    File parentFile = file.getParentFile();
    if (parentFile != null) {
        file = new File(parentFile.getAbsoluteFile().getCanonicalFile(), file.getName());
    }

    File absoluteFile = file.getAbsoluteFile();
    String canonicalPath = absoluteFile.getCanonicalPath();
    String absolutePath = file.getAbsolutePath();

    //if the absolute canonical path is the same as the absolute path, we don't believe it is a link
    return !canonicalPath.equals(absolutePath);

    //org.apache.commons.io.FileUtils is supposed to have a method for this, but the versions in maven (1.3, 1.3.1, 1.4) don't seem to.
    //return org.apache.commons.io.FileUtils.isSymlink(file);
}

From source file:eu.annocultor.utils.OntologySubtractor.java

private static void checkSrcAndDstDirs(File sourceDir, File destinationDir) throws Exception, IOException {

    if (!sourceDir.isDirectory()) {
        throw new Exception("Directory expected but this found: " + sourceDir.getCanonicalPath());
    }// w w w .  ja v  a  2s.  c om
    if (!destinationDir.isDirectory()) {
        throw new Exception("Directory expected but this found: " + destinationDir.getCanonicalPath());
    }
    if (!destinationDir.canWrite()) {
        throw new Exception("Directory is not writeable: " + destinationDir.getCanonicalPath());
    }
}

From source file:com.edgenius.core.util.ZipFileUtil.java

/**
 * Creates a ZIP file and places it in the current working directory. The zip file is compressed
 * at the default compression level of the Deflater.
 * //www .j  a v  a2s . c  o  m
 * @param listToZip. Key is file or directory, value is parent directory which will remove from given file/directory because 
 * compression only save relative directory.  For example, c:\geniuswiki\data\repository\somefile, if value is c:\geniuswiki, then only 
 * \data\repository\somefile will be saved.  It is very important, the value must be canonical path, ie, c:\my document\geniuswiki, 
 * CANNOT like this "c:\my doc~1\" 
 * 
 * 
 */
public static void createZipFile(String zipFileName, Map<File, String> listToZip, boolean withEmptyDir)
        throws ZipFileUtilException {
    ZipOutputStream zop = null;
    try {
        zop = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
        zop.setMethod(ZipOutputStream.DEFLATED);
        zop.setLevel(Deflater.DEFAULT_COMPRESSION);

        for (Entry<File, String> entry : listToZip.entrySet()) {
            File file = entry.getKey();
            if (!file.exists()) {
                log.warn("Unable to find file " + file + " to zip");
                continue;
            }
            if (file.isDirectory()) {
                Collection<File> list = FileUtils.listFiles(file, null, true);
                for (File src : list) {
                    addEntry(zop, src, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                }
                if (withEmptyDir) {
                    final List<File> emptyDirs = new ArrayList<File>();
                    if (file.list().length == 0) {
                        emptyDirs.add(file);
                    } else {
                        //I just don't know how quickly to find out all empty sub directories recursively. so use below hack:
                        FileUtils.listFiles(file, FileFilterUtils.falseFileFilter(), new IOFileFilter() {
                            //JDK1.6 @Override
                            public boolean accept(File f) {
                                if (!f.isDirectory())
                                    return false;

                                int size = f.listFiles().length;
                                if (size == 0) {
                                    emptyDirs.add(f);
                                }
                                return true;
                            }

                            //JDK1.6 @Override
                            public boolean accept(File arg0, String arg1) {
                                return true;
                            }
                        });
                    }
                    for (File src : emptyDirs) {
                        addEntry(zop, null, createRelativeDir(src.getCanonicalPath(), entry.getValue()));
                    }
                }
            } else {
                addEntry(zop, file, createRelativeDir(file.getCanonicalPath(), entry.getValue()));
            }

        }
    } catch (IOException e1) {
        throw new ZipFileUtilException(
                "An error has occurred while trying to zip the files. Error message is: ", e1);
    } finally {
        try {
            if (zop != null)
                zop.close();
        } catch (Exception e) {
        }
    }

}

From source file:FileStatus.java

public static void status(String fileName) throws IOException {
    System.out.println("---" + fileName + "---");

    // Construct a File object for the given file.
    File f = new File(fileName);

    // See if it actually exists
    if (!f.exists()) {
        System.out.println("file not found");
        System.out.println(); // Blank line
        return;/*from  w w  w  .  jav a2 s. c o m*/
    }
    // Print full name
    System.out.println("Canonical name " + f.getCanonicalPath());
    // Print parent directory if possible
    String p = f.getParent();
    if (p != null) {
        System.out.println("Parent directory: " + p);
    }
    // Check if the file is readable
    if (f.canRead()) {
        System.out.println("File is readable.");
    }
    // Check if the file is writable
    if (f.canWrite()) {
        System.out.println("File is writable.");
    }
    // Report on the modification time.
    Date d = new Date();
    d.setTime(f.lastModified());
    System.out.println("Last modified " + d);

    // See if file, directory, or other. If file, print size.
    if (f.isFile()) {
        // Report on the file's size
        System.out.println("File size is " + f.length() + " bytes.");
    } else if (f.isDirectory()) {
        System.out.println("It's a directory");
    } else {
        System.out.println("I dunno! Neither a file nor a directory!");
    }

    System.out.println(); // blank line between entries
}

From source file:com.sap.prd.mobile.ios.mios.FileUtils.java

static String getCanonicalPath(File f) throws IORuntimeException {
    try {/* ww  w.j a  va 2 s .c  o  m*/
        return f.getCanonicalPath();
    } catch (final IOException ex) {
        throw new IORuntimeException(ex.getMessage(), ex);
    }
}

From source file:packjacket.StaticUtils.java

/**
 * GZips the main log file/*w  w w .  jav  a 2  s  .  c om*/
 * @return the gzipped file
 * @throws IOException if any I/O error occurs
 */
public static File gzipLog() throws IOException {
    //Write out buffer of log file
    RunnerClass.nfh.flush();
    //Initialize log and gzip-log files
    File log = new File(RunnerClass.homedir + "pj.log");
    GZIPOutputStream out = new GZIPOutputStream(
            new FileOutputStream(new File(log.getCanonicalPath() + ".pjl")));
    FileInputStream in = new FileInputStream(log);

    //How many bytes to copy with each incrmental copy of file.
    int bufferSize = 4 * 1024;

    //Buffer into which data is read from source file
    byte[] buffer = new byte[bufferSize];
    //How many bytes read so far
    int bytesRead;
    //Runs until no bytes left to read from source
    while ((bytesRead = in.read(buffer)) >= 0)
        out.write(buffer, 0, bytesRead);
    //Close streams
    out.close();
    in.close();

    return new File(log.getCanonicalPath() + ".pjl");
}

From source file:com.canoo.webtest.util.FileUtil.java

/**
 * Writes a Stream to a file.// w  w w  . j  a va2  s.co m
 *
 * @param inputResponse
 * @param destfile
 * @param step
 * @throws StepExecutionException if something goes wrong
 */
public static void writeResponseStreamToFile(final WebResponse inputResponse, final File destfile,
        final Step step) {
    String canonicalPath = null;
    FileOutputStream outputStream = null;
    try {
        canonicalPath = destfile.getCanonicalPath();
        outputStream = new FileOutputStream(destfile);
        IOUtils.copy(inputResponse.getContentAsStream(), outputStream);
    } catch (IOException e) {
        throw new StepExecutionException("Could not find/write \"" + canonicalPath + "\".", step);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:com.bhbsoft.videoconference.record.convert.util.FlvFileHelper.java

public static File getNewDir(File dir, String name) throws IOException {
    File f = new File(dir, name);
    String baseName = f.getCanonicalPath();

    int recursiveNumber = 0;
    while (f.exists()) {
        f = new File(baseName + "_" + (recursiveNumber++));
    }//from   ww  w  . j  a va  2s. c  o  m
    f.mkdir();
    return f;
}

From source file:com.ms.commons.test.common.FileUtil.java

public static String convertURLToFilePath(URL url) {
    File f = convertURLToFile(url);
    if (f == null) {
        return null;
    }//ww  w  .  j a v  a 2s .  co m
    try {
        return f.getCanonicalPath();
    } catch (IOException e) {
        throw ExceptionUtil.wrapToRuntimeException(e);
    }
}