Example usage for java.io File getParent

List of usage examples for java.io File getParent

Introduction

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

Prototype

public String getParent() 

Source Link

Document

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Usage

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

/**
 * @param srcFile/*from   w ww .j  a v a 2s . com*/
 * @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:io.crate.testing.Utils.java

static void uncompressTarGZ(File tarFile, File dest) throws IOException {
    TarArchiveInputStream tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tarFile))));

    TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
    // tarIn is a TarArchiveInputStream
    while (tarEntry != null) {
        Path entryPath = Paths.get(tarEntry.getName());

        if (entryPath.getNameCount() == 1) {
            tarEntry = tarIn.getNextTarEntry();
            continue;
        }//from w w  w.  ja v  a2s  .  c  om

        Path strippedPath = entryPath.subpath(1, entryPath.getNameCount());
        File destPath = new File(dest, strippedPath.toString());

        if (tarEntry.isDirectory()) {
            destPath.mkdirs();
        } else {
            destPath.createNewFile();
            byte[] btoRead = new byte[1024];
            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
            int len;
            while ((len = tarIn.read(btoRead)) != -1) {
                bout.write(btoRead, 0, len);
            }

            bout.close();
            if (destPath.getParent().equals(dest.getPath() + "/bin")) {
                destPath.setExecutable(true);
            }
        }
        tarEntry = tarIn.getNextTarEntry();
    }
    tarIn.close();
}

From source file:com.docd.purefm.test.JavaFileTest.java

private static void testAgainstJavaIoFile(final JavaFile genericFile, final File javaFile) throws Throwable {
    assertEquals(javaFile, genericFile.toFile());
    assertEquals(javaFile.getName(), genericFile.getName());
    assertEquals(javaFile.getAbsolutePath(), genericFile.getAbsolutePath());
    assertEquals(javaFile.canRead(), genericFile.canRead());
    assertEquals(javaFile.canWrite(), genericFile.canWrite());
    assertEquals(javaFile.canExecute(), genericFile.canExecute());
    assertEquals(javaFile.exists(), genericFile.exists());
    assertEquals(javaFile.getPath(), genericFile.getPath());
    assertEquals(javaFile.getParent(), genericFile.getParent());
    assertEquals(javaFile.length(), genericFile.length());
    final File parentFile;
    final GenericFile genericParentFile = genericFile.getParentFile();
    if (genericParentFile == null) {
        parentFile = null;//  w w  w  .  j  av  a  2s  .  co  m
    } else {
        parentFile = genericParentFile.toFile();
    }
    assertEquals(javaFile.getParentFile(), parentFile);
    assertEquals(javaFile.length(), genericFile.length());
    try {
        assertEquals(FileUtils.isSymlink(javaFile), genericFile.isSymlink());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        assertEquals(javaFile.getCanonicalPath(), genericFile.getCanonicalPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
    assertEquals(javaFile.length(), genericFile.length());
    assertEquals(javaFile.lastModified(), genericFile.lastModified());
    assertEquals(javaFile.isDirectory(), genericFile.isDirectory());
    assertTrue(Arrays.equals(javaFile.list(), genericFile.list()));
    assertTrue(Arrays.equals(javaFile.listFiles(), genericFile.listFiles()));
}

From source file:FileUtils.java

/**
 * Rename the file to temporaty name with given prefix
 * /* ww w .  jav  a  2 s  . co  m*/
 * @param flFileToRename - file to rename
 * @param strPrefix - prefix to use
 * @throws IOException - error message
 */
public static void renameToTemporaryName(File flFileToRename, String strPrefix) throws IOException {
    assert strPrefix != null : "Prefix cannot be null.";

    String strParent;
    StringBuffer sbBuffer = new StringBuffer();
    File flTemp;
    int iIndex = 0;

    strParent = flFileToRename.getParent();

    // Generate new name for the file in a deterministic way
    do {
        iIndex++;
        sbBuffer.delete(0, sbBuffer.length());
        if (strParent != null) {
            sbBuffer.append(strParent);
            sbBuffer.append(File.separatorChar);
        }

        sbBuffer.append(strPrefix);
        sbBuffer.append("_");
        sbBuffer.append(iIndex);
        sbBuffer.append("_");
        sbBuffer.append(flFileToRename.getName());

        flTemp = new File(sbBuffer.toString());
    } while (flTemp.exists());

    // Now we should have unique name
    if (!flFileToRename.renameTo(flTemp)) {
        throw new IOException(
                "Cannot rename " + flFileToRename.getAbsolutePath() + " to " + flTemp.getAbsolutePath());
    }
}

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 ww.  j a v a 2 s.  c  om*/
 * @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:com.tesora.dve.common.PEFileUtils.java

/**
 * Write the text out to the specified filename.
 * //w  ww  . j av  a 2  s  .  co  m
 * @param fileName
 * @param text
 * @param overwriteContents
 * @throws Exception
 */
public static void writeToFile(File file, String text, boolean overwriteContents) throws PEException {
    BufferedWriter bw = null;
    try {
        if (file.exists() && !overwriteContents)
            throw new PEException("File '" + file.getCanonicalPath() + "' already exists");

        createDirectory(file.getParent());

        bw = new BufferedWriter(new FileWriter(file));
        bw.write(text);
    } catch (Exception e) {
        throw new PEException("Failed to write to file", e);
    } finally {
        if (bw != null) {
            try {
                bw.close();
            } catch (Exception e) {
                // Eat it
            }
        }
    }
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

private static boolean isSymlink(File file) throws IOException {
    File fileInCanonicalDir = null;
    if (file.getParent() == null) {
        fileInCanonicalDir = file;//  ww  w  .  j  a  va2 s .com
    } else {
        File canonicalDir = file.getParentFile().getCanonicalFile();
        fileInCanonicalDir = new File(canonicalDir, file.getName());
    }
    return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
}

From source file:com.quinsoft.zeidon.utils.JoeUtils.java

/**
 * Returns java.io.File for a file matching path using CASE-INSENSITIVE file
 * matching.  This makes it easier for us to run on Windows.
 *
 * @param path/*from  ww  w.  jav  a 2 s. c  o  m*/
 * @return
 */
public static File getFile(String path) {
    try {
        File file = new File(path);
        if (file.exists())
            return file;

        // Try searching for the file without regard to case.
        String parentPath = file.getParent();
        if (StringUtils.isBlank(parentPath))
            return file; // No parent path so just return.

        File dir = new File(parentPath);
        NameFileFilter filter = new NameFileFilter(file.getName(), IOCase.INSENSITIVE);
        String[] files = dir.list(filter);
        if (files == null)
            return file; // We probably didn't find a directory so just return the unknown file.

        if (files.length == 1)
            return new File(parentPath + File.separator + files[0]);

        if (files.length > 1)
            throw new ZeidonException("Found multiple matching entries for %s", path);

        // We didn't find an exact match so just return.
        return file;
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).prependFilename(path);
    }
}

From source file:com.vvote.verifierlibrary.utils.io.IOUtils.java

/**
 * Utility class to extract a zip file//from w w w  .j a v  a2  s . c  o m
 * 
 * @param filepath
 * @return the location of the extract zip file
 * @throws IOException
 */
public static String extractZipFile(String filepath) throws IOException {

    if (IOUtils.checkExtension(FileType.ZIP, filepath)) {
        try (ZipFile zipFile = new ZipFile(filepath)) {

            // files in zip file
            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            // current zip directory
            File zipDirectory = new File(filepath);

            // output directory - doesn't include the .zip extension
            File outputDirectory = new File(
                    IOUtils.join(zipDirectory.getParent(), IOUtils.getFileNameWithoutExtension(filepath)));

            // make directory if not exists
            if (!outputDirectory.exists()) {
                outputDirectory.mkdir();
            }

            InputStream is = null;
            FileOutputStream fos = null;
            byte[] bytes = null;

            int length = 0;

            // loop over each file in zip file
            while (entries.hasMoreElements()) {
                ZipEntry zipEntry = entries.nextElement();

                String entryName = zipEntry.getName();

                // current output file
                File file = new File(IOUtils.join(outputDirectory.getPath(), entryName));

                File currentOutputFile = new File(getFilePathWithoutExtension(file.getPath()));

                if (currentOutputFile.exists()) {
                    if (getFileNameWithoutExtension(entryName)
                            .contains(CommitFileNames.WBB_UPLOAD.getFileName())) {

                        try (ZipFile currentZipFile = new ZipFile(file)) {
                            Enumeration<? extends ZipEntry> currentZipEntries = currentZipFile.entries();

                            long currentUncompressedZipSize = currentZipEntries.nextElement().getSize();
                            long currentDirectorySize = FileUtils.sizeOfDirectory(currentOutputFile);

                            if (currentUncompressedZipSize == currentDirectorySize) {
                                continue;
                            }
                        }
                    }
                }

                // if directory make it
                if (entryName.endsWith("/")) {
                    file.mkdirs();
                } else {

                    // write current input zip file to output location
                    is = zipFile.getInputStream(zipEntry);
                    fos = new FileOutputStream(file);
                    bytes = new byte[1024];

                    while ((length = is.read(bytes)) >= 0) {
                        fos.write(bytes, 0, length);
                    }
                    is.close();
                    fos.close();
                }
            }

            return outputDirectory.getPath();
        }
    }
    logger.error("Provided filepath: {} does not point to a valid zip file", filepath);
    throw new IOException("Provided filepath: " + filepath + " does not point to a valid zip file");
}

From source file:com.symbian.driver.core.processors.EmulatorPreProcessor.java

/**
 * @param lSisFile/*from   w  w w  .jav a 2  s . c  o  m*/
 * @return All the files backed up for the emulator.
 * @throws ParseException
 * @throws IOException
 * @throws FileNotFoundException
 * 
 * @deprecated This needs to use the emulator ROM tool
 */
public static HashMap<File, File> backupEmulator(File lSisFile) throws IOException, FileNotFoundException {
    HashMap<File, File> lEmulatorHashBackup = new HashMap<File, File>();

    try {
        if (Epoc.isTargetEmulator(TDConfig.getInstance().getPreference(TDConfig.PLATFORM))) {
            File lPackageFile = new File(lSisFile.getParent() + File.separator + "testDriverPackage.pkg");
            if (!lPackageFile.isFile()) {
                throw new IOException("Could not find the Package file.");
            }

            BufferedReader lReposIn = new BufferedReader(new FileReader(lPackageFile));

            String lFileLoc = null;
            while ((lFileLoc = lReposIn.readLine()) != null) {
                String[] lSplitFileLoc = lFileLoc.split("\"-\"");

                if (lSplitFileLoc.length == 2) {
                    String lSymbianPathLiteral = lSplitFileLoc[1].substring(0, lSplitFileLoc[1].length() - 1);

                    File lEmulatorOrginal = new File(
                            TDConfig.getInstance().getPreferenceFile(TDConfig.EPOC_ROOT) + File.separator
                                    + ModelUtils.getEpoc32RelPlatVar() + File.separator
                                    + new File(lSymbianPathLiteral).getName());
                    File lEmulatorBackup = backupFile(lEmulatorOrginal);

                    if (lEmulatorBackup != null) {
                        lEmulatorHashBackup.put(lEmulatorOrginal, lEmulatorBackup);
                    }

                    //look into z drive as well

                    lEmulatorOrginal = new File(TDConfig.getInstance().getPreferenceFile(TDConfig.EPOC_ROOT)
                            + File.separator + ModelUtils.getEpoc32RelPlatVar() + File.separator + "Z"
                            + lSymbianPathLiteral.substring(2).replace('\\', File.separatorChar));
                    lEmulatorBackup = backupFile(lEmulatorOrginal);

                    if (lEmulatorBackup != null) {
                        lEmulatorHashBackup.put(lEmulatorOrginal, lEmulatorBackup);
                    }

                }
            }
        }
    } catch (ParseException lParseException) {
        LOGGER.log(Level.WARNING, "Could not backup emulator file due to configuration issue", lParseException);
    }
    return lEmulatorHashBackup;
}