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:net.emotivecloud.scheduler.drp4one.ConfigManager.java

private static void createDefaultConfigFile(File fileObject) throws Exception {
    log.debug("File " + fileObject.getAbsolutePath() + " didn't exist. Creating one with default values...");
    System.out.println(/*ww  w.  j a va 2  s  .  c  o  m*/
            "File " + fileObject.getAbsolutePath() + " didn't exist. Creating one with default values...");

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

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

    //Copy file.
    log.debug("Copying file " + fileObject.getName());
    InputStream streamIn = ConfigManager.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) {
        log.error("Couldn't close input stream");
        log.error(ex.getMessage());
    }
    try {
        streamOut.close();
    } catch (IOException ex) {
        log.error("Couldn't close file output stream");
        log.error(ex.getMessage());
    }
}

From source file:com.pactera.edg.am.metamanager.extractor.util.AntZip.java

public static void zip(String sourceDir, String zipFile) {

    OutputStream os;// w  w  w .j  ava 2 s .  c  o  m

    try {

        os = new FileOutputStream(zipFile);

        BufferedOutputStream bos = new BufferedOutputStream(os);

        ZipOutputStream zos = new ZipOutputStream(bos);

        File file = new File(sourceDir);

        String basePath = null;

        if (file.isDirectory()) {

            basePath = file.getPath();

        } else {// ??

            basePath = file.getParent();

        }

        zipFile(file, basePath, zos);

        zos.closeEntry();

        zos.close();

    } catch (Exception e) {

        e.printStackTrace();

    }

}

From source file:models.Template.java

public static String upload(String name, String description, File template, String userRegistered,
        Boolean isHidden) {//from  w  w w.ja  va  2s  .  co  m
    try {
        FileStringReader reader = new FileStringReader(template);
        String text = reader.read();

        if (!Helper.isUtf8(text)) {
            return "File must be in Plaintext (UTF 8).";
        }

        String author = userRegistered;

        Date now = new Date();
        Template temp = new Template(name, template.getName(), author, now, description, 4);
        temp.userRegistered = userRegistered;
        temp.isHidden = isHidden;
        temp.save();

        int dotPos = template.getName().lastIndexOf(".");
        String newName;
        String extension = null;

        if (dotPos != -1) {
            extension = template.getName().substring(dotPos);
            newName = temp.id + "_" + name + extension;
        } else {
            newName = temp.id + "_" + name;
        }

        File copy_to = new File(Play.applicationPath.getAbsolutePath() + "/public/templates/" + newName);

        //System.out.println(copy_to.getAbsolutePath());
        Helper.copy(template, copy_to);

        temp.filename_ = newName;
        temp.calculateForm();
        temp.save();

        Helper helper = new Helper();
        if (!extension.equals(".tex")) {
            helper.templateToImage(temp);
        } else {
            Substitution sub = new Substitution(temp.textFile);
            Map map = new HashMap(temp.templates_);
            Iterator it = map.keySet().iterator();

            while (it.hasNext()) {
                String key = (String) it.next();
                map.put(key, key);
            }
            sub.replace(map);
            File replaced_file = new File(
                    Play.applicationPath.getAbsolutePath() + "/public/tmp/" + temp.filename_);
            File destination = new File(replaced_file.getParent());
            FileStringWriter writer = new FileStringWriter(replaced_file);

            writer.write(sub.getText());

            helper.texToPdf(replaced_file, destination);

            String[] source_name = temp.filename_.split(".tex");

            File source = new File(destination + "/" + source_name[0] + ".pdf");
            destination = new File(
                    Play.applicationPath.getAbsolutePath() + "/template/" + source_name[0] + ".pdf.jpg");

            helper.pdfToImage(source, destination);

        }

        return null;
    } catch (Exception e) {
        System.out.println(e.toString());
        return e.toString();
    }
}

From source file:FileTableHTML.java

public static String makeHTMLTable(String dirname) {
    // Look up the contents of the directory
    File dir = new File(dirname);
    String[] entries = dir.list();

    // Set up an output stream we can print the table to.
    // This is easier than concatenating strings all the time.
    StringWriter sout = new StringWriter();
    PrintWriter out = new PrintWriter(sout);

    // Print the directory name as the page title
    out.println("<H1>" + dirname + "</H1>");

    // Print an "up" link, unless we're already at the root
    String parent = dir.getParent();
    if ((parent != null) && (parent.length() > 0))
        out.println("<A HREF=\"" + parent + "\">Up to parent directory</A><P>");

    // Print out the table
    out.print("<TABLE BORDER=2 WIDTH=600><TR>");
    out.print("<TH>Name</TH><TH>Size</TH><TH>Modified</TH>");
    out.println("<TH>Readable?</TH><TH>Writable?</TH></TR>");
    for (int i = 0; i < entries.length; i++) {
        File f = new File(dir, entries[i]);
        out.println("<TR><TD>" + (f.isDirectory() ? "<a href=\"" + f + "\">" + entries[i] + "</a>" : entries[i])
                + "</TD><TD>" + f.length() + "</TD><TD>" + new Date(f.lastModified()) + "</TD><TD align=center>"
                + (f.canRead() ? "x" : " ") + "</TD><TD align=center>" + (f.canWrite() ? "x" : " ")
                + "</TD></TR>");
    }//from ww  w  .  j  ava 2  s.  c  o  m
    out.println("</TABLE>");
    out.close();

    // Get the string of HTML from the StringWriter and return it.
    return sout.toString();
}

From source file:de.pksoftware.springstrap.sapi.util.WebappZipper.java

/**
 * Unzip it//from ww  w .  jav  a2 s  .c o m
 * @param zipFile input zip file
 * @param output zip file output folder
 */
public static void unzip(String zipFile, String outputFolder) {
    logger.info("Unzipping {} into {}.", zipFile, outputFolder);

    byte[] buffer = new byte[1024];

    try {

        //get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);

            logger.debug("Unzipping: {}", newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
            ze = zis.getNextEntry();
        }

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

        logger.debug("Unzipping {} completed.", zipFile);

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.pieframework.runtime.utils.ArtifactManager.java

public static String generateDeployPath(String basePath, boolean unArchive, String query) {
    String result = null;//from  w  w w.  j av  a 2s .co  m

    //Locate the files in the local artifact cache
    Configuration.log().debug("artifact location:" + basePath + " query:" + query);
    List<File> flist = ResourceLoader.findPath(basePath, query);

    //System.out.println(flist.size() +" "+basePath +" "+query);

    if (!flist.isEmpty()) {
        String archivePath = getArchivePath(flist);
        if (!StringUtils.empty(archivePath)) {
            //Create a temp location
            File archiveFile = new File(archivePath);
            String tmpPath = ResourceLoader.getDeployRoot() + ResourceLoader.getResourceName(query)
                    + File.separatorChar + TimeUtils.getCurrentTimeStamp() + File.separatorChar
                    + FilenameUtils.getName(archiveFile.getParent());

            File tmpDir = new File(tmpPath);
            if (tmpDir.isDirectory() && !tmpDir.exists()) {
                tmpDir.mkdirs();
            }

            //Unarchive the file
            try {
                Zipper.unzip(archivePath, tmpPath);
                result = tmpPath;
            } catch (Exception e) {
                //TODO throw error
                e.printStackTrace();
            }

        } else {
            result = getCommonPathRoot(flist);
        }
    } else {
        throw new RuntimeException(
                "Failed locating path for artifact. searchroot:" + basePath + " query:" + query);
    }
    return result;
}

From source file:eu.optimis.ics.core.util.PropertiesReader.java

/**
 * Creates a default properties file if it doesn't exist
 * @param fileObject    properties file/* w w w . j  ava 2s  .com*/
 * @throws Exception  Unexcepted error occurs
 */
private static void createDefaultConfigFile(File fileObject) throws Exception {

    log.info("ics.core.util.PropertiesReader.createDefaultConfigFile(): File " + fileObject.getAbsolutePath()
            + " doesn't exist. Creating one with default values...");

    // Create parent directories.
    log.info("ics.core.util.PropertiesReader.createDefaultConfigFile(): Creating parent directories.");
    new File(fileObject.getParent()).mkdirs();

    // Create an empty file to copy the contents of the default file.
    log.info("ics.core.util.PropertiesReader.createDefaultConfigFile(): Creating empty file.");
    new File(fileObject.getAbsolutePath()).createNewFile();

    // Copy file.
    log.info("ics.core.util.PropertiesReader.createDefaultConfigFile(): Copying file " + fileObject.getName());
    InputStream streamIn = PropertiesReader.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 ignore) {
        log.error("ics.core.util.PropertiesReader.createDefaultConfigFile(): Couldn't close input stream");
    }

    try {
        streamOut.close();
    } catch (IOException ignore) {
        log.error(
                "ics.core.util.PropertiesReader.createDefaultConfigFile(): Couldn't close file output stream");
    }
}

From source file:net.ftb.minecraft.MCInstaller.java

public static void extractLegacyJson(File newLoc) {
    try {//from  www .j a v  a2s .  c o  m
        if (!new File(newLoc.getParent()).exists())
            new File(newLoc.getParent()).mkdirs();
        if (newLoc.exists())
            newLoc.delete();//we want to have the current version always!!!
        URL u = LaunchFrame.class.getResource("/launch/legacypack.json");
        org.apache.commons.io.FileUtils.copyURLToFile(u, newLoc);
    } catch (Exception e) {
        Logger.logError("Error extracting legacy json to maven directory");
    }
}

From source file:net.ontopia.topicmaps.entry.XMLConfigSource.java

/**
 * INTERNAL: Returns a collection containing the topic map sources
 * created by reading the configuration file.
 *//*  ww  w  .ja  v a 2 s  .c  om*/
public static List<TopicMapSourceIF> readSources(String config_file, Map<String, String> environ) {
    if (environ == null)
        environ = new HashMap<String, String>(1);
    // add CWD entry
    if (!environ.containsKey(CWD)) {
        File file = new File(config_file);
        if (!file.exists())
            throw new OntopiaRuntimeException("Config file '" + config_file + "' does not exist.");
        environ.put(CWD, file.getParent());
    }

    return readSources(new InputSource(URIUtils.toURL(new File(config_file)).toString()), environ);
}

From source file:com.admc.jcreole.CreoleParseTest.java

@Parameters
public static List<Object[]> creoleFiles() throws IOException {
    if (!pCreoleInRoot.isDirectory())
        throw new IllegalStateException("Dir missing: " + pCreoleInRoot.getAbsolutePath());
    if (!nCreoleInRoot.isDirectory())
        throw new IllegalStateException("Dir missing: " + nCreoleInRoot.getAbsolutePath());
    if (pWorkOutRoot.exists())
        FileUtils.deleteDirectory(pWorkOutRoot);
    pWorkOutRoot.mkdir();//  ww w. j  av  a 2 s. com
    if (nWorkOutRoot.exists())
        FileUtils.deleteDirectory(nWorkOutRoot);
    nWorkOutRoot.mkdir();
    List<Object[]> params = new ArrayList<Object[]>();
    File eFile;
    for (File f : FileUtils.listFiles(pCreoleInRoot, new String[] { "creole" }, true)) {
        eFile = new File(f.getParentFile(), f.getName().replaceFirst("\\..*", "") + ".html");
        params.add(new Object[] { f, eFile,
                (eFile.isFile()
                        ? new File(pWorkOutRoot,
                                f.getParentFile().equals(pCreoleInRoot) ? eFile.getName()
                                        : (f.getParent().substring(pCreoleInRootPath.length()) + FSEP
                                                + eFile.getName()))
                        : null),
                Boolean.TRUE });
    }
    String name;
    for (File f : FileUtils.listFiles(nCreoleInRoot, new String[] { "creole" }, true)) {
        name = f.getName().replaceFirst("\\..*", "") + ".html";
        params.add(new Object[] { f, null,
                new File(nWorkOutRoot,
                        f.getParentFile().equals(nCreoleInRoot) ? name
                                : (f.getParent().substring(nCreoleInRootPath.length()) + FSEP + name)),
                Boolean.FALSE });
    }
    return params;
}