Example usage for java.io File getParentFile

List of usage examples for java.io File getParentFile

Introduction

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

Prototype

public File getParentFile() 

Source Link

Document

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

Usage

From source file:org.paxml.util.PaxmlUtils.java

public static File getSiblingFile(File base, String name, boolean appendName) {
    return new File(base.getParentFile(), appendName ? base.getName() : name);
}

From source file:org.eclipse.wst.json.core.internal.download.HttpClientProvider.java

private static File download(File file, URL url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    OutputStream out = null;/*  w ww .j a v  a2s  .c o  m*/
    file.getParentFile().mkdirs();
    try {
        HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        Builder builder = RequestConfig.custom();
        HttpHost proxy = getProxy(target);
        if (proxy != null) {
            builder = builder.setProxy(proxy);
        }
        RequestConfig config = builder.build();
        HttpGet request = new HttpGet(url.toURI());
        request.setConfig(config);
        response = httpclient.execute(target, request);
        InputStream in = response.getEntity().getContent();
        out = new BufferedOutputStream(new FileOutputStream(file));
        copy(in, out);
        return file;
    } catch (Exception e) {
        logWarning(e);
        ;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return null;
}

From source file:com.alta189.bukkit.script.event.EventScanner.java

public static void writeEvents() {
    File file = new File(BScript.getInstance().getDataFolder(), "events.txt");
    if (file.exists()) {
        file.delete();//ww w . j ava 2s .  co  m
    }

    if (file.getParentFile() != null && !file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
    }
    StringBuilder builder = new StringBuilder();
    builder.append("Bukkit Event Classes").append(LINE_SEPARATOR).append("####################")
            .append(LINE_SEPARATOR).append(LINE_SEPARATOR);

    for (Map.Entry<String, Class<? extends Event>> entry : bukkitEvent.entrySet()) {
        String className = entry.getValue().getCanonicalName();
        if (className == null) {
            className = entry.getValue().getName();
        }
        builder.append("Full Name: ").append(className).append(LINE_SEPARATOR).append("Simple Name: ")
                .append(entry.getKey()).append(LINE_SEPARATOR).append(LINE_SEPARATOR);
    }

    builder.append("Plugin Event Classes").append(LINE_SEPARATOR).append("####################")
            .append(LINE_SEPARATOR).append(LINE_SEPARATOR);

    for (Map.Entry<Plugin, Set<Class<? extends Event>>> entry : pluginEvents.entrySet()) {

        builder.append("Plugin: ").append(entry.getKey().getName()).append(LINE_SEPARATOR)
                .append("---------------------").append(LINE_SEPARATOR).append(LINE_SEPARATOR);

        for (Class<? extends Event> clazz : entry.getValue()) {
            String className = clazz.getCanonicalName();
            if (className == null) {
                className = clazz.getName();
            }
            String simpleName = clazz.getSimpleName();
            builder.append("Full Name: ").append(entry.getKey().getName()).append(":").append(className)
                    .append(LINE_SEPARATOR).append("Simple Name: ").append(entry.getKey().getName()).append(":")
                    .append(simpleName);

            if (simpleNameEvents.get(simpleName) != null) {
                builder.append(LINE_SEPARATOR).append("Simplest Name: ").append(simpleName);
            }
            builder.append(LINE_SEPARATOR).append(LINE_SEPARATOR);
        }
    }
    builder.append(LINE_SEPARATOR);
    try {
        FileUtils.write(file, builder.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.googlecode.fascinator.common.JsonConfig.java

/**
 * Gets the system-wide configuration file from the default config dir. If
 * the file doesn't exist, a default is copied to the config dir.
 * /*from  www  .j  a  va  2 s  .  c o  m*/
 * @return the system JSON file
 * @throws IOException if there was an error reading or writing the system
 *             configuration file
 */
public static File getSystemFile() throws IOException {
    File configFile = new File(CONFIG_DIR, SYSTEM_CONFIG_FILE);
    if (!configFile.exists()) {
        configFile.getParentFile().mkdirs();
        OutputStream out = new FileOutputStream(configFile);
        IOUtils.copy(JsonConfig.class.getResourceAsStream("/" + SYSTEM_CONFIG_FILE), out);
        out.close();
        log.info("Default configuration copied to '{}'", configFile);
    }
    return configFile;
}

From source file:com.bluexml.tools.miscellaneous.PrepareSIDEModulesMigration.java

protected static void renameFile(final String versionInProjectName, String versionInProjectName2, File f) {
    String replace = f.getName().replace(versionInProjectName, versionInProjectName2);
    File file = new File(f.getParentFile(), replace);
    if (!f.getName().equals(replace)) {
        System.out.println("PrepareSIDEModulesMigration.reNameResources() try to rename file :" + f.getName()
                + " to " + file.getName());
        boolean renameTo = f.renameTo(file);
        System.out.println("PrepareSIDEModulesMigration.reNameResources() rename :" + renameTo);
    }// w w w.  j a va2s.co m
}

From source file:eu.trentorise.opendata.josman.test.GitTest.java

private static File createFile(Repository repository, String filePath) {

    try {//from w ww  . ja va  2 s  . com
        // create the file

        File targetFile = new File(repository.getDirectory().getParent(), filePath);
        File parent = targetFile.getParentFile();
        if (!parent.exists() && !parent.mkdirs()) {
            throw new IllegalStateException("Couldn't create dir: " + parent);
        }

        targetFile.createNewFile();

        PrintWriter pw = new PrintWriter(targetFile);
        pw.println("hello");
        pw.close();

        // run the add-call
        new Git(repository).add().addFilepattern(filePath).call();

        return targetFile;

    } catch (Exception ex) {
        throw new RuntimeException("Error while creating file!", ex);
    }
}

From source file:au.org.ala.delta.util.FileUtils.java

/**
 * Attempts to make a relative path from path to file. If path and file have different roots (like drives under Windows), then
 * the path cannot be made relative, and in these cases this function will return null.
 * //from  w ww  .j av a 2s . c  om
 * @param path the source path
 * @param file the file/directory that will be made relative to the source path
 * @return either relative path from path to file, or null indicating that no common ancestor could be found (i.e. path cannot be made relative).
 * 
 */
public static String makeRelativeTo(String path, File file) {
    String relativePath;
    if (file.isAbsolute()) {
        File dataSetPath = new File(path);

        File parent = parent(file, dataSetPath);
        File commonParent = dataSetPath;
        String prefix = "";
        while (!parent.equals(commonParent) && commonParent != null) {
            prefix += ".." + File.separatorChar;
            commonParent = commonParent.getParentFile();
            parent = parent(file, commonParent);
        }

        if (commonParent == null) {
            // No common parent, cannot make relative
            return null;
        }

        String filePath = file.getAbsolutePath();
        String parentPath = parent.getAbsolutePath();

        int relativePathIndex = filePath.indexOf(parentPath) + parentPath.length();
        if (!parentPath.endsWith(File.separator)) {
            relativePathIndex++;
        }
        if (relativePathIndex > filePath.length()) {
            relativePathIndex = filePath.length();
        }
        relativePath = prefix + filePath.substring(relativePathIndex);
        if (StringUtils.isEmpty(relativePath)) {
            relativePath = ".";
        }
    } else {
        relativePath = file.getPath();
    }
    return relativePath;

}

From source file:com.nttec.everychan.ui.tabs.LocalHandler.java

public static TabModel getTabModel(String filename, Resources resources) {
    File file = new File(filename);
    if (file.exists() && !file.isDirectory()) {
        String lfilename = filename.toLowerCase(Locale.US);
        if (!lfilename.endsWith(".zip") && !lfilename.endsWith(".mht") && !lfilename.endsWith(".mhtml")) {
            file = file.getParentFile();
            filename = file.getAbsolutePath();
        }//from w  w  w. java  2 s  .  c  o m
    }

    ReadableContainer zip = null;
    UrlPageModel pageModel;
    String pageTitle;
    try {
        zip = ReadableContainer.obtain(file);
        Pair<String, UrlPageModel> p = MainApplication.getInstance().serializer
                .loadPageInfo(zip.openStream(DownloadingService.MAIN_OBJECT_FILE));
        pageTitle = p.getLeft();
        pageModel = p.getRight();
    } catch (Exception e) {
        Logger.e(TAG, e);
        MainApplication.getInstance().database.removeSavedThread(filename);
        return null;
    } finally {
        try {
            if (zip != null)
                zip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    TabModel model = new TabModel();
    model.type = TabModel.TYPE_LOCAL;
    model.id = new Random().nextLong();
    model.title = pageTitle;
    model.pageModel = pageModel;
    model.hash = CryptoUtils.computeMD5(filename);
    try {
        model.webUrl = MainApplication.getInstance().getChanModule(pageModel.chanName).buildUrl(pageModel);
    } catch (IllegalArgumentException e) {
        model.webUrl = null;
    } catch (NullPointerException e) {
        return null;
    }
    model.localFilePath = filename;
    model.forceUpdate = true;
    return model;
}

From source file:de.mprengemann.intellij.plugin.androidicons.util.RefactorHelper.java

public static void move(Project project, final String description, final List<File> sources,
        final List<File> targets) throws IOException {
    copy(project, description, sources, targets);
    RunnableHelper.runWriteCommand(project, new Runnable() {
        @Override// w w w. ja  v  a  2 s . co  m
        public void run() {
            try {
                File dir = null;
                for (File source : sources) {
                    if (dir == null) {
                        dir = source.getParentFile();
                    }
                    FileUtils.forceDelete(source);
                }

                if (dir != null) {
                    if (dir.isDirectory()) {
                        File[] images = dir.listFiles(new FilenameFilter() {
                            @Override
                            public boolean accept(File file, String s) {
                                String mimetype = new MimetypesFileTypeMap().getContentType(file);
                                String type = mimetype.split("/")[0];
                                return type.equals("image");
                            }
                        });
                        if (images == null || images.length == 0) {
                            FileUtils.forceDelete(dir);
                        }
                    }
                }
            } catch (IOException ignored) {
            }
        }
    }, description);
}

From source file:io.joynr.util.JoynrUtil.java

public static void writeResource(byte[] byteResource, String fileName) throws IOException {
    File file = new File(fileName);
    if (!file.exists()) {
        createDir(file.getParentFile().getAbsolutePath());
    }//from ww w . java 2 s. c o  m

    if (!file.createNewFile()) {
        logger.debug("Creating file " + fileName + " failed.");
    }

    FileOutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(fileName);
        outputStream.write(byteResource);

    } catch (FileNotFoundException e) {
        logger.error("Writing file " + fileName + " failed.", e);
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }

    }

}