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:de.pixida.logtest.designer.commons.SelectFileButton.java

public static Button createButtonWithFileSelection(final TextField inputFieldShowingPath, final String icon,
        final String title, final String fileMask, final String fileMaskDescription) {
    final Button selectLogFileButton = new Button("Select");
    selectLogFileButton.setGraphic(Icons.getIconGraphics(icon));
    selectLogFileButton.setOnAction(event -> {
        final FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle(title);//ww  w .  j  a  v a 2 s . c  om
        if (StringUtils.isNotBlank(fileMask) && StringUtils.isNotBlank(fileMaskDescription)) {
            fileChooser.getExtensionFilters()
                    .add(new FileChooser.ExtensionFilter(fileMaskDescription, fileMask));
        }
        File initialDirectory = new File(inputFieldShowingPath.getText().trim());
        if (!initialDirectory.isDirectory()) {
            initialDirectory = initialDirectory.getParentFile();
        }
        if (initialDirectory == null || !initialDirectory.isDirectory()) {
            if (lastFolder != null) {
                initialDirectory = lastFolder;
            } else {
                initialDirectory = new File(".");
            }
        }
        fileChooser.setInitialDirectory(initialDirectory);
        final File selectedFile = fileChooser.showOpenDialog(((Node) event.getTarget()).getScene().getWindow());
        if (selectedFile != null) {
            inputFieldShowingPath.setText(selectedFile.getAbsolutePath());
            final File parent = selectedFile.getParentFile();
            if (parent != null && parent.isDirectory()) {
                lastFolder = parent;
            }
        }
    });
    return selectLogFileButton;
}

From source file:net.refractions.udig.document.source.ShpDocUtils.java

/**
 * Gets the relative path with the url as the parent path and the absolute path as the child
 * path.//from  w  w  w. j  a  v a2s .  com
 * 
 * @param url
 * @param absolutePath
 * @return relative path
 */
public static String getRelativePath(URL url, String absolutePath) {
    if (absolutePath != null && absolutePath.trim().length() > 0) {
        try {
            final File parentFile = new File(new URI(url.toString()));
            final File parentDir = parentFile.getParentFile();
            final File childFile = new File(absolutePath);
            return parentDir.toURI().relativize(childFile.toURI()).getPath();
        } catch (URISyntaxException e) {
            // Should not happen as shapefile should be a valid file
            e.printStackTrace();
        }
    }
    return null;
}

From source file:ar.com.init.agros.reporting.ReportExporter.java

public static void exportReportXLS(JasperPrint jp, String path)
        throws JRException, FileNotFoundException, IOException {

    //ARREGLO PARA REPORTES CON NOMBRES DE MAS DE 31 CARACTERES
    String oldName = jp.getName().replace("/", "-");
    jp.setName(oldName);//from w  w w. j a v  a2s. c  om
    if (oldName.length() >= 31) {
        jp.setName(oldName.substring(0, 31));
    }
    //ARREGLO PARA REPORTES CON NOMBRES DE MAS DE 31 CARACTERES

    JRXlsExporter exporter = new JRXlsExporter();

    File outputFile = new File(path);
    File parentFile = outputFile.getParentFile();
    if (parentFile != null) {
        parentFile.mkdirs();
    }
    FileOutputStream fos = new FileOutputStream(outputFile);

    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, fos);
    exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.FALSE);

    exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.FALSE);
    exporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS, Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.TRUE);

    exporter.exportReport();

    fos.close();

    logger.info("XLS Report exported: " + path);

    //ARREGLO PARA REPORTES CON NOMBRES DE MAS DE 31 CARACTERES
    jp.setName(oldName);
}

From source file:Main.java

public static OutputStream getOutputStream(File dir, String fileName) throws Exception {
    File outFile = new File(dir, fileName);
    // as this could be dir=.../maps fileName=preview/file.jpg
    // we need to make sure the preview dir exists, and if it does not, we must make it
    File parent = outFile.getParentFile();
    if (!parent.isDirectory() && !parent.mkdirs()) { // if it does not exist and i cant make it
        throw new RuntimeException("can not create dir " + parent);
    }//  w w  w. j av a 2s  .  c  o m
    return new FileOutputStream(outFile);
}

From source file:com.github.pemapmodder.pocketminegui.utils.Utils.java

private static File installWindowsPHP(File home, InstallProgressReporter progress) {
    progress.report(0.0);/*  ww  w  . jav  a  2s.c  o m*/
    try {
        String link = System.getProperty("os.arch").contains("64")
                ? "https://bintray.com/artifact/download/pocketmine/PocketMine/PHP_7.0.3_x64_Windows.tar.gz"
                : "https://bintray.com/artifact/download/pocketmine/PocketMine/PHP_7.0.3_x86_Windows.tar.gz";
        URL url = new URL(link);
        InputStream gz = url.openStream();
        GzipCompressorInputStream tar = new GzipCompressorInputStream(gz);
        TarArchiveInputStream is = new TarArchiveInputStream(tar);
        TarArchiveEntry entry;
        while ((entry = is.getNextTarEntry()) != null) {
            if (!entry.isDirectory()) {
                String name = entry.getName();
                byte[] buffer = new byte[(int) entry.getSize()];
                IOUtils.read(is, buffer);
                File real = new File(home, name);
                real.getParentFile().mkdirs();
                IOUtils.write(buffer, new FileOutputStream(real));
            }
        }
        File output = new File(home, "bin/php/php.exe");
        progress.completed(output);
        return output;
    } catch (IOException e) {
        e.printStackTrace();
        progress.errored();
        return null;
    }
}

From source file:com.hightern.fckeditor.tool.UtilsFile.java

/**
 * Iterates over a base name and returns the first non-existent file.<br />
 * This method extracts a file's base name, iterates over it until the first non-existent appearance with <code>basename(n).ext</code>. Where n is a positive integer starting from one.
 * //w  w w .  jav a 2 s. c  om
 * @param file
 *            base file
 * @return first non-existent file
 */
public static File getUniqueFile(final File file) {
    if (!file.exists()) {
        return file;
    }

    File tmpFile = new File(file.getAbsolutePath());
    final File parentDir = tmpFile.getParentFile();
    int count = 1;
    final String extension = FilenameUtils.getExtension(tmpFile.getName());
    final String baseName = FilenameUtils.getBaseName(tmpFile.getName());
    do {
        tmpFile = new File(parentDir, baseName + "(" + count++ + ")." + extension);
    } while (tmpFile.exists());
    return tmpFile;
}

From source file:net.rptools.maptool.util.AssetExtractor.java

public static void extract() throws Exception {
    new Thread() {
        @Override//from   w  ww  . j  a v  a 2s. com
        public void run() {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {
                return;
            }
            File file = chooser.getSelectedFile();
            File newDir = new File(file.getParentFile(),
                    file.getName().substring(0, file.getName().lastIndexOf('.')) + "_images");

            JLabel label = new JLabel("", JLabel.CENTER);
            JFrame frame = new JFrame();
            frame.setTitle("Campaign Image Extractor");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(400, 75);
            frame.add(label);
            SwingUtil.centerOnScreen(frame);
            frame.setVisible(true);
            Reader r = null;
            OutputStream out = null;
            PackedFile pakfile = null;
            try {
                newDir.mkdirs();

                label.setText("Loading campaign ...");
                pakfile = new PackedFile(file);

                Set<String> files = pakfile.getPaths();
                XStream xstream = new XStream();
                int count = 0;
                for (String filename : files) {
                    count++;
                    if (filename.indexOf("assets") < 0) {
                        continue;
                    }
                    r = pakfile.getFileAsReader(filename);
                    Asset asset = (Asset) xstream.fromXML(r);
                    IOUtils.closeQuietly(r);

                    File newFile = new File(newDir, asset.getName() + ".jpg");
                    label.setText("Extracting image " + count + " of " + files.size() + ": " + newFile);
                    if (newFile.exists()) {
                        newFile.delete();
                    }
                    newFile.createNewFile();
                    out = new FileOutputStream(newFile);
                    FileUtil.copyWithClose(new ByteArrayInputStream(asset.getImage()), out);
                }
                label.setText("Done.");
            } catch (Exception ioe) {
                MapTool.showInformation("AssetExtractor failure", ioe);
            } finally {
                if (pakfile != null)
                    pakfile.close();
                IOUtils.closeQuietly(r);
                IOUtils.closeQuietly(out);
            }
        }
    }.start();
}

From source file:br.com.RatosDePC.Brpp.compiler.BrppCompiler.java

public static boolean compile(String path) {
    setFile(FileUtils.getBrinodirectory() + System.getProperty("file.separator") + "Arduino");
    setFile(getFile()/*from w  w  w.j a v a2  s . c om*/
            .concat(path.substring(path.lastIndexOf(System.getProperty("file.separator")), path.length() - 5)));
    setFile(getFile()
            .concat(path.substring(path.lastIndexOf(System.getProperty("file.separator")), path.length() - 4)));
    setFile(getFile().concat("ino"));
    File ino = new File(getFile());
    if (!ino.exists()) {
        try {
            ino.getParentFile().mkdirs();
            ino.createNewFile();
        } catch (IOException e) {

        }
    }
    try {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        String code = new String(encoded);
        JSONArray Keywords = JSONUtils.getKeywords();
        @SuppressWarnings("unchecked")
        Iterator<JSONObject> iterator = Keywords.iterator();
        while (iterator.hasNext()) {
            JSONObject key = iterator.next();
            String arg = (String) key.get("arg");
            if (arg.equals("false")) {
                code = code.replace((String) key.get("translate"), (String) key.get("arduino"));
            } else {
                code = code.replaceAll((String) key.get("translate"), (String) key.get("arduino"));
            }
        }

        try (FileWriter file = new FileWriter(getFile())) {
            file.write(code);
        }
        System.out.println(code);
        return true;

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;

}

From source file:com.jcalvopinam.core.Unzipping.java

private static void joinAndUnzipFile(File inputFile, CustomFile customFile) throws IOException {

    ZipInputStream is = null;//  w  w  w .  ja v a 2 s. c  o m
    File path = inputFile.getParentFile();

    List<InputStream> fileInputStream = new ArrayList<>();
    for (String fileName : path.list()) {
        if (fileName.startsWith(customFile.getFileName()) && fileName.endsWith(Extensions.ZIP.getExtension())) {
            fileInputStream.add(new FileInputStream(String.format("%s%s", customFile.getPath(), fileName)));
            System.out.println(String.format("File found: %s", fileName));
        }
    }

    if (fileInputStream.size() > 0) {
        String fileNameOutput = String.format("%s%s", customFile.getPath(), customFile.getFileName());
        OutputStream os = new BufferedOutputStream(new FileOutputStream(fileNameOutput));
        try {
            System.out.println("Please wait while the files are joined: ");

            ZipEntry ze;
            for (InputStream inputStream : fileInputStream) {
                is = new ZipInputStream(inputStream);
                ze = is.getNextEntry();
                customFile.setFileName(String.format("%s_%s", REBUILT, ze.getName()));

                byte[] buffer = new byte[CustomFile.BYTE_SIZE];

                for (int readBytes; (readBytes = is.read(buffer, 0, CustomFile.BYTE_SIZE)) > -1;) {
                    os.write(buffer, 0, readBytes);
                    System.out.print(".");
                }
            }
        } finally {
            os.flush();
            os.close();
            is.close();
            renameFinalFile(customFile, fileNameOutput);
        }
    } else {
        throw new FileNotFoundException("Error: The file not exist!");
    }
    System.out.println("\nEnded process!");
}

From source file:net.bpelunit.util.ZipUtil.java

public static void unzipFile(File zip, File dir) throws IOException {
    InputStream in = null;//w  w w  . ja v  a  2  s  . c  o  m
    OutputStream out = null;
    ZipFile zipFile = new ZipFile(zip);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (!entry.getName().endsWith("/")) {
            File unzippedFile = new File(dir, entry.getName());
            try {
                in = zipFile.getInputStream(entry);
                unzippedFile.getParentFile().mkdirs();

                out = new FileOutputStream(unzippedFile);

                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }
        }
    }
}