Example usage for java.io File getAbsoluteFile

List of usage examples for java.io File getAbsoluteFile

Introduction

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

Prototype

public File getAbsoluteFile() 

Source Link

Document

Returns the absolute form of this abstract pathname.

Usage

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static String getFileIfCanWrite(String path, String file) {
    File fileObj = new File(path, file);
    if (fileObj.canWrite()) {
        return fileObj.getAbsoluteFile().getAbsolutePath();
    }// ww  w .  j  a  v a2s .c  o m
    return null;
}

From source file:com.plugin.excel.xsd.node.store.impl.FileHelper.java

public static File copyFolder(Class clazz, List<String> files, File destination, String rootDirName) {

    File rootDir = null;//from w w w.ja  v  a 2 s. c o m

    if (clazz != null && files != null && !files.isEmpty()) {

        for (String file : files) {
            InputStream stream = clazz.getClassLoader().getResourceAsStream(file);
            try {
                File temp = new File(destination.getAbsoluteFile() + "/" + file);
                if (!file.contains(".")) {
                    temp.delete();
                    temp.mkdir();
                } else {
                    FileUtils.copyInputStreamToFile(stream, temp);
                }

                if (file.replaceAll("/", "").equalsIgnoreCase(rootDirName)) {
                    rootDir = temp;
                }

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

    }

    return rootDir;
}

From source file:arena.utils.FileUtils.java

/**
 * Used for checking path inheritances. This is useful for canonicalizing URLs that 
 * maybe don't exist, but we want to treat them as paths anyway.
 *//* ww  w.  j av a  2s  .  c  o m*/
public static boolean isDescendant(File parent, File child, File commonBase) {
    if (child.equals(parent)) {
        return true;
    } else {
        // Start by checking canonicals if possible
        try {
            String canonicalParent = parent.getAbsoluteFile().getCanonicalPath();
            String canonicalChild = child.getAbsoluteFile().getCanonicalPath();
            if (canonicalChild.startsWith(canonicalParent)) {
                return true;
            }
        } catch (IOException err) {
            // assume the files are imaginary ... try with the manual construction below
        }

        // If canonicals don't match, we're dealing with symlinked files, so if we can
        // build a path from the parent to the child, 
        String childOCValue = constructOurCanonicalVersion(child, commonBase);
        String parentOCValue = constructOurCanonicalVersion(parent, commonBase);
        return childOCValue.startsWith(parentOCValue);
    }
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static String getChildDirectoryIfExists(String parent, String child) {
    File parentFile = new File(parent);
    if (parentFile.exists() && parentFile.isDirectory()) {
        File childFile = new File(parentFile, child);
        if (childFile.exists()) {
            return childFile.getAbsoluteFile().getAbsolutePath();
        }/*from w  ww.j  av  a2  s  .  c o  m*/
    }
    return null;
}

From source file:dk.netarkivet.common.utils.ZipUtils.java

/** Gunzip a single gzipped file into the given file. Unlike with the gzip()
 * command-line tool, the original file is not deleted.
 *
 * @param fromFile A gzipped file to unzip.
 * @param toFile The file that the contents of fromFile should be gunzipped
 * into.  This file must be in an existing directory.  Existing contents of
 * this file will be overwritten./*from w w w.  java  2s  . c o  m*/
 */
public static void gunzipFile(File fromFile, File toFile) {
    ArgumentNotValid.checkNotNull(fromFile, "File fromFile");
    ArgumentNotValid.checkTrue(fromFile.canRead(), "fromFile must be readable");
    ArgumentNotValid.checkNotNull(toFile, "File toFile");
    ArgumentNotValid.checkTrue(toFile.getAbsoluteFile().getParentFile().canWrite(),
            "toFile must be in a writeable dir");
    try {
        GZIPInputStream in = new LargeFileGZIPInputStream(new FileInputStream(fromFile));
        FileUtils.writeStreamToFile(in, toFile);
    } catch (IOException e) {
        throw new IOFailure("Error ungzipping '" + fromFile + "'", e);
    }
}

From source file:com.csipsimple.backup.SipProfileJson.java

/**
 * Save current sip configuration/*w  w w.  ja  v  a 2s  . c om*/
 * 
 * @param ctxt
 * @return
 */
public static boolean saveSipConfiguration(Context ctxt, String filePassword) {
    File dir = PreferencesWrapper.getConfigFolder(ctxt);
    if (dir != null) {
        Date d = new Date();
        File file = new File(dir.getAbsoluteFile() + File.separator + "backup_"
                + DateFormat.format("yy-MM-dd_kkmmss", d) + ".json");
        Log.d(THIS_FILE, "Out dir " + file.getAbsolutePath());

        JSONObject configChain = new JSONObject();
        try {
            configChain.put(KEY_ACCOUNTS, serializeSipProfiles(ctxt));
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Impossible to add profiles", e);
        }
        try {
            configChain.put(KEY_SETTINGS, serializeSipSettings(ctxt));
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Impossible to add profiles", e);
        }

        try {
            // Create file
            OutputStream fos = new FileOutputStream(file);
            if (!TextUtils.isEmpty(filePassword)) {
                Cipher c;
                try {
                    c = Cipher.getInstance("AES");
                    SecretKeySpec k = new SecretKeySpec(filePassword.getBytes(), "AES");
                    c.init(Cipher.ENCRYPT_MODE, k);
                    fos = new CipherOutputStream(fos, c);
                } catch (NoSuchAlgorithmException e) {
                    Log.e(THIS_FILE, "NoSuchAlgorithmException :: ", e);
                } catch (NoSuchPaddingException e) {
                    Log.e(THIS_FILE, "NoSuchPaddingException :: ", e);
                } catch (InvalidKeyException e) {
                    Log.e(THIS_FILE, "InvalidKeyException :: ", e);
                }
            }
            FileWriter fstream = new FileWriter(file.getAbsoluteFile());
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(configChain.toString(2));
            // Close the output stream
            out.close();
            return true;
        } catch (Exception e) {
            // Catch exception if any
            Log.e(THIS_FILE, "Impossible to save config to disk", e);
            return false;
        }
    }
    return false;
}

From source file:net.morimekta.idltool.IdlUtils.java

public static Git getCacheRepository(File cacheDir, String repository) throws IOException, GitAPIException {
    File repoCache = getCacheDirectory(cacheDir, repository);

    Runtime runtime = Runtime.getRuntime();
    if (!repoCache.exists()) {
        Process p = runtime//from  w w w  . j ava 2 s. c  o  m
                .exec(new String[] { "git", "clone", repository, repoCache.getAbsoluteFile().toString() });
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    } else {
        Process p = runtime.exec(new String[] { "git", "fetch", "origin", "-p" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "add", "-A" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "reset", "origin/master", "--hard" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
    return Git.open(repoCache);
}

From source file:org.dkpro.lab.Util.java

public static void createSymbolicLink(File aSource, File aTarget) throws IOException {
    if (aTarget.exists()) {
        throw new FileExistsException(aTarget);
    }/*from ww w .j ava  2  s .c o m*/

    File parentDir = aTarget.getAbsoluteFile().getParentFile();
    if (parentDir != null && !parentDir.exists()) {
        FileUtils.forceMkdir(parentDir);
    }

    // Try Java 7 methods
    try {
        Object fromPath = MethodUtils.invokeExactMethod(aSource, "toPath", new Object[0]);
        Object toPath = MethodUtils.invokeExactMethod(aTarget, "toPath", new Object[0]);
        Object options = Array.newInstance(Class.forName("java.nio.file.attribute.FileAttribute"), 0);
        MethodInvoker inv = new MethodInvoker();
        inv.setStaticMethod("java.nio.file.Files.createSymbolicLink");
        inv.setArguments(new Object[] { toPath, fromPath, options });
        inv.prepare();
        inv.invoke();
        return;
    } catch (ClassNotFoundException e) {
        // Ignore
    } catch (NoSuchMethodException e) {
        // Ignore
    } catch (IllegalAccessException e) {
        // Ignore
    } catch (InvocationTargetException e) {
        if ("java.nio.file.FileAlreadyExistsException".equals(e.getTargetException().getClass().getName())) {
            throw new FileExistsException(aTarget);
        }
    }

    // If the Java 7 stuff is not available, fall back to Runtime.exec
    String[] cmdline = { "ln", "-s", aSource.getAbsolutePath(), aTarget.getAbsolutePath() };
    Execute exe = new Execute();
    exe.setVMLauncher(false);
    exe.setCommandline(cmdline);
    exe.execute();
    if (exe.isFailure()) {
        throw new IOException("Unable to create symlink from [" + aSource + "] to [" + aTarget + "]");
    }
}

From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java

/**
 * Un zip a file to a destination folder.
 * @param zipFile the zip file//  w w  w.j a va  2s.  c o m
 * @param outputFolder the output folder
 */
public static void unZipFile(final String zipFile, final String outputFolder) {

    LogUtil.setLogString("UnZip the File", true);
    final byte[] buffer = new byte[1024];
    int len;
    try {
        // create output directory is not exists
        final File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }
        // get the zip file content
        final ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        final StringBuilder outFolderPath = new StringBuilder();
        final StringBuilder fileLogPath = new StringBuilder();
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null) {
            final String fileName = zipEntry.getName();
            final File newFile = new File(
                    outFolderPath.append(outputFolder).append(File.separator).append(fileName).toString());
            LogUtil.setLogString(
                    fileLogPath.append("file unzip : ").append(newFile.getAbsoluteFile()).toString(), true);
            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();
            final FileOutputStream fos = new FileOutputStream(newFile);

            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            fileLogPath.setLength(0);
            outFolderPath.setLength(0);
        }

        zis.closeEntry();
        zis.close();

        LogUtil.setLogString("Done", true);

    } catch (IOException ex) {
        LOGGER.error("Error in unzip file", ex);
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.JasperReportsCache.java

/**
 * Starts the report creation process/*from  ww  w  .  j  a va 2  s  . c  o  m*/
 * @param fileName the XML file name of the report definition
 * @param recrdSet the recordset to use to fill the labels
 */
public static ReportCompileInfo checkReport(final File file) {
    File cachePath = getCachePath();
    String fileName = file.getName();
    File compiledPath = getCompiledFile(file);

    AppResourceIFace appRes = AppContextMgr.getInstance().getResource(fileName);

    File reportFileFromCache = new File(cachePath.getAbsoluteFile() + File.separator + fileName);

    // Check to see if it needs to be recompiled, if it doesn't need compiling then
    // call "compileComplete" directly to have it start filling the labels
    // otherswise create the compiler runnable and have it be compiled 
    // asynchronously

    Timestamp apTime = appRes.getTimestampModified() == null ? appRes.getTimestampCreated()
            : appRes.getTimestampModified();
    boolean needsCompiling = apTime == null || !compiledPath.exists()
            || apTime.getTime() > reportFileFromCache.lastModified();

    //log.debug(appRes.getTimestampModified().getTime()+" > "+reportFileFromCache.lastModified() +"  "+(appRes.getTimestampModified().getTime() > reportFileFromCache.lastModified()));
    //log.debug(compiledPath.exists());
    //log.debug("needsCompiling "+needsCompiling);
    return new ReportCompileInfo(reportFileFromCache, compiledPath, needsCompiling);
}