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:Main.java

/**
 *
 * @param fi/*w w  w  .  j  a  va 2 s  . co m*/
 * @param newName
 * @return
 */
public static File renameTo(File fi, String newName) {
    /* File.renameTo is a abstract file rename finction .
     * I override this function which return File but boolean.
     * To get the new File obj , you can separately rename the file you want to .
     * Example code:
     *
    File f = new File("D:\\abc.def") ;
    File tmp = renameTo(f,"a.a") ;
    renameTo(tmp,"b.b") ;
     */
    //It can rename the File to the same dir.
    String dest = fi.getParent();
    dest += "\\" + newName;
    //System.out.println("Rename To : "+dest) ;
    File newNameFile = new File(dest);
    fi.renameTo(newNameFile);
    return newNameFile;
}

From source file:com.microsoft.azure.hdinsight.util.HDInsightJobViewUtils.java

private static void extractJobViewResource() {
    URL url = HDInsightJobViewUtils.class.getResource("/resources/" + HTML_ZIP_FILE_NAME);
    URL hdinsightJobViewJarUrl = HDInsightJobViewUtils.class
            .getResource("/resources/" + HDINSIGHT_JOB_VIEW_JAR_NAME);
    File indexRootFile = new File(PluginUtil.pluginFolder + File.separator + HTML_FOLDER_NAME);
    if (!indexRootFile.exists()) {
        indexRootFile.mkdir();//  w  w  w .  ja  va 2 s  .c o  m
    }
    File toFile = new File(indexRootFile.getAbsolutePath(), HTML_ZIP_FILE_NAME);
    File hdinsightJobViewToFile = new File(indexRootFile.getAbsolutePath(), HDINSIGHT_JOB_VIEW_JAR_NAME);
    try {
        FileUtils.copyURLToFile(url, toFile);
        FileUtils.copyURLToFile(hdinsightJobViewJarUrl, hdinsightJobViewToFile);
        HDInsightJobViewUtils.unzip(toFile.getAbsolutePath(), toFile.getParent());
        DefaultLoader.getIdeHelper().setProperty(HDINSIGHT_JOBVIEW_EXTRACT_FLAG, "true");
    } catch (IOException e) {
        Activator.getDefault().log("Extract Job View Folder", e);
    }
}

From source file:com.microsoft.azuretools.hdinsight.util.HDInsightJobViewUtils.java

private static void extractJobViewResource() {
    URL url = HDInsightJobViewUtils.class.getResource("/resources/" + HTML_ZIP_FILE_NAME);
    URL hdinsightJobViewJarUrl = HDInsightJobViewUtils.class
            .getResource("/resources/" + HDINSIGHT_JOB_VIEW_JAR_NAME);
    if (url == null || hdinsightJobViewJarUrl == null) {
        DefaultLoader.getUIHelper().showError("Cann't find Spark job view resources", "Job view");
        return;/*from w ww . j a  va2 s .  co  m*/
    }
    File indexRootFile = new File(PluginUtil.pluginFolder, HDINSIGIHT_FOLDER_NAME);
    if (indexRootFile.exists()) {
        FileUtils.deleteQuietly(indexRootFile);
    }
    File htmlRootFile = new File(indexRootFile.getPath(), "html");
    htmlRootFile.mkdirs();
    File htmlToFile = new File(htmlRootFile.getAbsolutePath(), HTML_ZIP_FILE_NAME);
    File hdinsightJobViewToFile = new File(indexRootFile, HDINSIGHT_JOB_VIEW_JAR_NAME);
    try {
        FileUtils.copyURLToFile(url, htmlToFile);
        FileUtils.copyURLToFile(hdinsightJobViewJarUrl, hdinsightJobViewToFile);
        HDInsightJobViewUtils.unzip(htmlToFile.getAbsolutePath(), htmlToFile.getParent());
        DefaultLoader.getIdeHelper().setProperty(HDINSIGHT_JOBVIEW_EXTRACT_FLAG, "true");
    } catch (IOException e) {
        DefaultLoader.getUIHelper().showError("Extract Job View Folder error:" + e.getMessage(), "Job view");
    }
}

From source file:edu.kit.dama.util.ZipUtils.java

/**
 * Zip a single file to target directory. zip file add the '.zip' extension
 * to filename.//from   ww w  .j  av  a2  s  .  c  o m
 *
 * @param pTargetDir Directory to store the zip file.
 * @param pSourceFile Source file.
 * @throws IOException If there are any IO errors.
 */
public static void zipSingleFile(File pTargetDir, File pSourceFile) throws IOException {
    File zipFile = new File(pTargetDir.getAbsolutePath() + File.separator + pSourceFile.getName() + ".zip");
    zip(new File[] { pSourceFile }, pSourceFile.getParent(), zipFile);
}

From source file:eu.freme.eservices.epublishing.Unzipper.java

public static void unzip(ZipInputStream zis, File outputFolder) throws IOException {
    //create output directory is not exists

    if (!outputFolder.exists() && !outputFolder.mkdirs()) {
        throw new IOException("Cannot create directory " + outputFolder);
    }/*  w  ww. jav a2  s  .  co m*/

    //get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(outputFolder, fileName);

        logger.debug("file unzip : " + newFile.getAbsoluteFile());

        //create all non exists folders
        //else you will hit FileNotFoundException for compressed folder
        File parentDir = newFile.getParentFile();
        if (!parentDir.exists() && !parentDir.mkdirs()) {
            throw new IOException("Cannot create directory " + newFile.getParent());
        }

        if (ze.isDirectory()) {
            newFile.mkdirs();
        } else {
            try (FileOutputStream fos = new FileOutputStream(newFile)) {
                IOUtils.copyLarge(zis, fos);
            }
        }
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
}

From source file:com.bluexml.side.m2.repositoryBuilder.Builder.java

private static void applyOptionalJob(File rootPlugins, String option, String filePath)
        throws Exception, IOException {
    if (option.equals("-makeDot")) {
        writeDotFile(rootPlugins, filePath);
        System.out.println("graph dot file generated :" + filePath);
    } else if (option.equals("-patchPom")) {
        List<ModuleConstraint> res = Builder.getModulesConstraint(rootPlugins);
        // add dependency plugin used by SIDE
        ModuleConstraint McForMavenDependeciesPlugins = new ModuleConstraint(
                "org.apache.maven.plugins.maven-dependency-plugin", null, "maven-plugin", "2.0", "2.0");
        res.add(McForMavenDependeciesPlugins);

        File file = new File(filePath);
        if (!file.exists()) {
            System.err.println("File do not exist :" + file);
        }/*w ww.j av  a 2  s .co m*/
        List<File> poms = new ArrayList<File>();
        for (ModuleConstraint moduleConstraint : res) {
            File destFile = new File(file.getParent(), res.indexOf(moduleConstraint) + "_.pom");
            FileUtils.copyFile(file, destFile);
            List<ModuleConstraint> res_ = new ArrayList<ModuleConstraint>();
            res_.add(moduleConstraint);
            writePomFile(destFile, res_);
            System.out.println("pom Patched" + destFile);
            poms.add(destFile);
        }
        // write pom.sh script that call go-offline for each patched poms
        Builder.writeShellScript(new File(file.getParent(), "pom.sh"), poms);
    }
}

From source file:com.littcore.io.util.ZipUtils.java

public static void unzip(File srcZipFile, File targetFilePath, boolean isDelSrcFile) throws IOException {
    if (!targetFilePath.exists()) //?
        targetFilePath.mkdirs();/*  w w w. j  av a 2s  .  c o m*/
    ZipFile zipFile = new ZipFile(srcZipFile);

    Enumeration fileList = zipFile.getEntries();
    ZipEntry zipEntry = null;
    while (fileList.hasMoreElements()) {
        zipEntry = (ZipEntry) fileList.nextElement();
        if (zipEntry.isDirectory()) //?
        {
            File subFile = new File(targetFilePath, zipEntry.getName());
            if (!subFile.exists()) //??
                subFile.mkdir();
            continue;
        } else //?
        {
            File targetFile = new File(targetFilePath, zipEntry.getName());
            if (logger.isDebugEnabled()) {
                logger.debug("" + targetFile.getName());
            }

            if (!targetFile.exists()) {
                File parentPath = new File(targetFile.getParent());
                if (!parentPath.exists()) //????????
                    parentPath.mkdirs();
                //targetFile.createNewFile();
            }

            InputStream in = zipFile.getInputStream(zipEntry);
            FileOutputStream out = new FileOutputStream(targetFile);
            int len;
            byte[] buf = new byte[BUFFERED_SIZE];
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.close();
            in.close();
        }
    }
    zipFile.close();
    if (isDelSrcFile) {
        boolean isDeleted = srcZipFile.delete();
        if (isDeleted) {
            if (logger.isDebugEnabled()) {
                logger.debug("");
            }
        }
    }
}

From source file:es.bsc.autonomic.powermodeller.configuration.CoreConfiguration.java

private static void createDefaultConfigFile(File fileObject) throws Exception {
    logger.debug("File " + fileObject.getAbsolutePath() + " didn't exist. Creating one with default values...");

    //Create parent directories.
    logger.debug("Creating parent directories.");
    new File(fileObject.getParent()).mkdirs();

    //Create an empty file to copy the contents of the default file.
    logger.debug("Creating empty file.");
    new File(fileObject.getAbsolutePath()).createNewFile();

    //Copy file.//from  ww w  .ja v  a  2  s  . c o  m
    logger.debug("Copying file " + fileObject.getName());
    InputStream streamIn = CoreConfiguration.class.getResourceAsStream("/" + fileObject.getName());
    FileOutputStream streamOut = new FileOutputStream(fileObject.getAbsolutePath());
    byte[] buf = new byte[8192];
    while (true) {
        int length = streamIn.read(buf);
        if (length < 0) {
            break;
        }
        streamOut.write(buf, 0, length);
    }

    //Close streams after copying.
    try {
        streamIn.close();
    } catch (IOException ex) {
        logger.error("Couldn't close input stream");
        logger.error(ex.getMessage());
    }
    try {
        streamOut.close();
    } catch (IOException ex) {
        logger.error("Couldn't close file output stream");
        logger.error(ex.getMessage());
    }

    setPosixFilePermissions(fileObject.toPath(), PosixFilePermissions.fromString("rwxr-xr-x"));
}

From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.util.SVMHMMUtils.java

/**
 * Creates a new file in the same directory as {@code featureVectorsFile} and replaces the first
 * token (outcome label) by its corresponding integer number from the bi-di map
 *
 * @param featureVectorsFile file/*from   ww w  .  ja  v  a2s  .  c om*/
 * @param labelsToIntegers   mapping
 * @return new file
 */
public static File replaceLabelsWithIntegers(File featureVectorsFile, BidiMap labelsToIntegers)
        throws IOException {
    File result = new File(featureVectorsFile.getParent(), "mappedLabelsToInt_" + featureVectorsFile.getName());
    PrintWriter pw = new PrintWriter(new FileOutputStream(result));

    for (String line : FileUtils.readLines(featureVectorsFile)) {
        // split on the first whitespaces, keep the rest
        String[] split = line.split("\\s", 2);
        String label = split[0];
        String remainingContent = split[1];

        // find the integer
        Integer intOutput = (Integer) labelsToIntegers.get(label);

        // print to the output stream
        pw.printf("%d %s%n", intOutput, remainingContent);
    }

    IOUtils.closeQuietly(pw);

    return result;
}

From source file:org.opentides.util.FileUtil.java

/**
 * Helper class to read certain file and return contents as string. The file
 * must be located relative to classpath.
 * /*from w ww. j  av  a  2 s . c  o m*/
 * @param filename
 * @return
 */
public static String backupFile(File source) {
    File backup = new File(source.getParent() + "/~" + source.getName());
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(source)));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(backup)));
        return FileUtil.backupFile(reader, writer, source.getAbsolutePath());
    } catch (FileNotFoundException fe) {
        String msg = "Failed to find file for backup [" + source.getAbsolutePath() + "].";
        _log.error(msg, fe);
        throw new InvalidImplementationException(msg, fe);
    }
}