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.aurel.track.exchange.latex.exporter.LaTeXExportBL.java

/**
 * Serializes the docx content into the response's output stream
 * @param response/*from ww w.  jav  a 2  s .  c o  m*/
 * @param wordMLPackage
 * @return
 */
public static String prepareReportResponse(HttpServletResponse response, TWorkItemBean workItem,
        ReportBeans reportBeans, TPersonBean user, Locale locale, String templateDir, String templateFile) {
    ReportBeansToLaTeXConverter rl = new ReportBeansToLaTeXConverter();
    File pdf = rl.generatePdf(workItem, reportBeans.getItems(), true, locale, user, "", "", false,
            new File(templateFile), new File(templateDir));
    String fileName = workItem.getSynopsis() + ".pdf";
    String contentType = "application/pdf";
    if (pdf.length() < 10) {
        pdf = new File(pdf.getParent() + "/errors.txt");
        fileName = workItem.getSynopsis() + ".txt";
        contentType = "text";
    }
    OutputStream outputStream = null;
    try {
        response.reset();
        response.setHeader("Content-Type", contentType);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response);
        outputStream = response.getOutputStream();
        InputStream is = new FileInputStream(pdf);
        IOUtils.copy(is, outputStream);
        is.close();
    } catch (FileNotFoundException e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (IOException e) {
        LOGGER.error("Getting the output stream failed with " + e.getMessage());
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }

    //            Docx4J.save(wordMLPackage, outputStream, Docx4J.FLAG_NONE);
    //            //wordMLPackage.save(outputStream);
    //            /*SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
    //         saver.save(outputStream);*/
    //         } catch (Exception e) {
    //            LOGGER.error("Exporting the docx failed with throwable " + e.getMessage());
    //            LOGGER.debug(ExceptionUtils.getStackTrace(e));
    //         }
    return null;
}

From source file:ArchiveUtil.java

private static void extractEntry(File entryFile, JarInputStream jis, JarEntry entry, boolean deleteOnExit)
        throws IOException {
    File parent = new File(entryFile.getParent());
    if (!parent.exists())
        parent.mkdirs();//from  ww  w  .j  a  va2 s .co m
    ResourceUtil.copy(jis, new FileOutputStream(entryFile));
    entryFile.setLastModified(entry.getTime());
    if (deleteOnExit) {
        parent.deleteOnExit();
        entryFile.deleteOnExit();
    }
}

From source file:net.lightbody.bmp.proxy.jetty.util.JarResource.java

public static void extract(Resource resource, File directory, boolean deleteOnExit) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Extract " + resource + " to " + directory);
    JarInputStream jin = new JarInputStream(resource.getInputStream());
    JarEntry entry = null;/* w  w w. j av a  2  s . com*/
    while ((entry = jin.getNextJarEntry()) != null) {
        File file = new File(directory, entry.getName());
        if (entry.isDirectory()) {
            // Make directory
            if (!file.exists())
                file.mkdirs();
        } else {
            // make directory (some jars don't list dirs)
            File dir = new File(file.getParent());
            if (!dir.exists())
                dir.mkdirs();

            // Make file
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(file);
                IO.copy(jin, fout);
            } finally {
                IO.close(fout);
            }

            // touch the file.
            if (entry.getTime() >= 0)
                file.setLastModified(entry.getTime());
        }
        if (deleteOnExit)
            file.deleteOnExit();
    }
}

From source file:com.hazelcast.simulator.utils.FileUtils.java

public static void writeObject(Object o, File file) {
    File tmpFile = new File(file.getParent(), file.getName() + ".tmp");

    FileOutputStream stream = null;
    ObjectOutputStream outputStream = null;
    try {//from w w w  .j a  va2s .  co m
        stream = new FileOutputStream(tmpFile);
        outputStream = new ObjectOutputStream(stream);
        outputStream.writeObject(o);
    } catch (IOException e) {
        throw new FileUtilsException(e);
    } finally {
        closeQuietly(outputStream);
        closeQuietly(stream);
    }

    rename(tmpFile, file);
}

From source file:com.izforge.izpack.util.IoHelper.java

/**
 * Returns the first existing parent directory in a path
 *
 * @param path path which should be scanned
 * @return the first existing parent directory in a path
 *//*from  w  ww. j  av  a 2s  . co  m*/
public static File existingParent(File path) {
    File result = path;
    while (!result.exists()) {
        if (result.getParent() == null) {
            return result;
        }
        result = result.getParentFile();
    }
    return result;
}

From source file:com.moss.posixfifosockets.PosixFifoSocket.java

public static void createFifo(File path) throws IOException {
    if (path.exists()) {
        throw new IOException("File already exists: " + path.getAbsolutePath());
    }//from  w w  w .jav a  2 s.  c o m
    if (!path.getParentFile().exists()) {
        throw new FileNotFoundException(path.getParent());
    }
    try {
        if (path.exists()) {
            throw new RuntimeException("Path really does exist: " + path.getAbsolutePath());
        }

        final Process p = Runtime.getRuntime().exec("mkfifo " + path.getAbsolutePath());
        int result = p.waitFor();
        if (result != 0) {

            String stdOut = read(p.getInputStream());
            String stdErr = read(p.getErrorStream());
            throw new IOException("Error creating fifo at " + path.getAbsolutePath() + ": Received error code "
                    + result + ", STDOUT: " + stdOut + ", STDERR: " + stdErr);
        } else if (!path.exists()) {
            throw new RuntimeException("mkfifo didn't do its job: " + path.getAbsolutePath());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:FileStatus.java

public static void status(String fileName) throws IOException {
    System.out.println("---" + fileName + "---");

    // Construct a File object for the given file.
    File f = new File(fileName);

    // See if it actually exists
    if (!f.exists()) {
        System.out.println("file not found");
        System.out.println(); // Blank line
        return;//from  w ww.j  av  a 2  s.c  o m
    }
    // Print full name
    System.out.println("Canonical name " + f.getCanonicalPath());
    // Print parent directory if possible
    String p = f.getParent();
    if (p != null) {
        System.out.println("Parent directory: " + p);
    }
    // Check if the file is readable
    if (f.canRead()) {
        System.out.println("File is readable.");
    }
    // Check if the file is writable
    if (f.canWrite()) {
        System.out.println("File is writable.");
    }
    // Report on the modification time.
    Date d = new Date();
    d.setTime(f.lastModified());
    System.out.println("Last modified " + d);

    // See if file, directory, or other. If file, print size.
    if (f.isFile()) {
        // Report on the file's size
        System.out.println("File size is " + f.length() + " bytes.");
    } else if (f.isDirectory()) {
        System.out.println("It's a directory");
    } else {
        System.out.println("I dunno! Neither a file nor a directory!");
    }

    System.out.println(); // blank line between entries
}

From source file:org.ubicompforall.cityexplorer.gui.ImportWebTab.java

/***
 * Extract database URLs from the web-page source code, given as the string text
 * @param text   the web-page source code
 * @return      new web-page source code with multiple "<A HREF='databaseX.sqlite'>databaseX</A>" only
 *//*from w  w w  . j a  va2 s . co  m*/
public static CopyOnWriteArrayList<DB> extractDBs(String text, String SERVER_URL) {
    webDBs = new CopyOnWriteArrayList<DB>(); //To avoid duplicates!
    Matcher m = Pattern.compile("<a.* href=\"([^>]+(sqlite|db|db3))\">([^<]+)</a>", Pattern.CASE_INSENSITIVE)
            .matcher(text);
    while (m.find()) {
        String filename = m.group(1);
        if (filename.charAt(0) == '/') {
            filename = SERVER_URL + filename;
        }
        //webDBs.add( new DB(URL.getParentFile().getParent(), URL.getParentFile().getName(), URL.getName(), m.group(3) ) );
        // group 0 is everything, group 1 is (www.and.so.on)
        try {
            URL url = new URL(filename);
            File file = new File(filename);
            debug(1, "URL is  " + url);
            webDBs.add(new DB(file.getParentFile().getParent(), file.getParentFile().getName(), file.getName(),
                    url));
            debug(1, "Added: " + filename + " " + m.group(3));
        } catch (MalformedURLException e) {
            debug(-1, e.getMessage());
        }
    }
    return webDBs;
}

From source file:eu.optimis.tf.ip.service.utils.PropertiesUtils.java

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

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

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

    // Copy file.
    log.info("TRUST: Copying file " + fileObject.getName());
    InputStream streamIn = PropertiesUtils.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;
        }//from  w ww.  ja  v  a  2s.  co m
        streamOut.write(buf, 0, length);
    }

    // Close streams after copying.
    try {
        streamIn.close();
    } catch (IOException ignore) {
        log.error("TRUST: Couldn't close input stream");
    }
    try {
        streamOut.close();
    } catch (IOException ignore) {
        log.error("TRUST: Couldn't close file output stream");
    }
}

From source file:hivemall.xgboost.NativeLibLoader.java

private static void tryLoadNativeLibFromResource(final String libName) {
    // Resolve the library file name with a suffix (e.g., dll, .so, etc.)
    String resolvedLibName = System.mapLibraryName(libName);

    if (!hasResource(libPath + resolvedLibName)) {
        if (!getOSName().equals("Mac")) {
            return;
        }//from  ww  w.  j av  a 2s  .  c  o m
        // Fix for openjdk7 for Mac
        // A detail of this workaround can be found in https://github.com/xerial/snappy-java/issues/6
        resolvedLibName = "lib" + libName + ".jnilib";
        if (hasResource(libPath + resolvedLibName)) {
            return;
        }
    }
    try {
        File tempFile = createTempFileFromResource(resolvedLibName,
                NativeLibLoader.class.getResourceAsStream(libPath + resolvedLibName));
        logger.info("Copyed the native library in JAR as " + tempFile.getAbsolutePath());
        addLibraryPath(tempFile.getParent());
    } catch (Exception e) {
        // Simply ignore it here
        logger.info(e.getMessage());
    }
}