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

public static ArrayList<File> getFilesInPath(String path) {
    File pathFile = new File(path);
    if (pathFile != null) {
        File[] files = pathFile.listFiles();
        ArrayList<File> result = new ArrayList<>();
        for (int i = 0; i < files.length; ++i) {
            result.add(files[i]);/*from  w  ww  .j a  va2s .com*/
        }
        result.add(0, pathFile.getParentFile());
        return result;
    } else {
        return null;
    }
}

From source file:Main.java

public static boolean isSymLink(File filePath) throws IOException {
    if (filePath == null)
        throw new NullPointerException("filePath cannot be null");
    File canonical;/*from ww w . j a  va 2s .com*/
    if (filePath.getParent() == null) {
        canonical = filePath;
    } else {
        File canonDir = filePath.getParentFile().getCanonicalFile();
        canonical = new File(canonDir, filePath.getName());
    }
    return !canonical.getCanonicalFile().equals(canonical.getAbsoluteFile());
}

From source file:Main.java

public static void copyAssetFile(AssetManager am, String assetName, File destBaseDir, boolean overwrite)
        throws IOException {
    File destFile = new File(destBaseDir.getAbsolutePath().concat(File.separator).concat(assetName));

    if (destFile.exists() && !overwrite)
        return;// w ww. j  a  va 2 s  .co  m

    if (overwrite) {
        destFile.delete();
    }
    destFile.getParentFile().mkdirs();

    InputStream is = null;
    OutputStream os = null;

    try {
        byte[] buff = new byte[4096];
        is = am.open(assetName, AssetManager.ACCESS_STREAMING);
        os = new FileOutputStream(destFile);

        while (true) {
            int nread = is.read(buff);
            if (nread <= 0)
                break;
            os.write(buff, 0, nread);
        }
    } finally {
        closeQuietly(is);
        closeQuietly(os);
    }
}

From source file:edu.unc.lib.dl.util.ZipFileUtil.java

private static boolean isFileInsideDirectory(File child, File parent) throws IOException {

    child = child.getCanonicalFile();//from   w ww .  j  a va  2  s.c om
    parent = parent.getCanonicalFile();

    while (child != null) {
        child = child.getParentFile();

        if (parent.equals(child))
            return true;
    }

    return false;

}

From source file:com.athena.chameleon.engine.threadpool.task.FileEncodingConvertTaskTest.java

/**
 * <pre>//from  www  . j  ava2 s  .  c  om
 *   ? ? ?  ??   ? ? ??  ?? .
 * </pre>
 * 
 * @throws java.lang.Exception
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    File[] fileList = new File(FileEncodingConvertTaskTest.class.getResource("/converter/orig").getFile())
            .listFiles();

    for (File file : fileList) {
        copy(file, new File(file.getParentFile().getParent() + File.separator + file.getName()));
    }
}

From source file:io.proleap.cobol.TestGenerator.java

public static void generateTestClass(final File cobolInputFile, final File outputDirectory,
        final String packageName) throws IOException {
    final File parentDirectory = cobolInputFile.getParentFile();
    final String inputFilename = getInputFilename(cobolInputFile);
    final File outputFile = new File(
            outputDirectory + "/" + inputFilename + OUTPUT_FILE_SUFFIX + JAVA_EXTENSION);

    final boolean createdNewFile = outputFile.createNewFile();

    if (createdNewFile) {
        LOG.info("Creating unit test {}.", outputFile);

        final PrintWriter pWriter = new PrintWriter(new FileWriter(outputFile));
        final String cobolInputFileName = cobolInputFile.getPath().replace("\\", "/");
        final CobolSourceFormat format = getCobolSourceFormat(parentDirectory);

        pWriter.write("package " + packageName + ";\n");
        pWriter.write("\n");
        pWriter.write("import java.io.File;\n");
        pWriter.write("\n");
        pWriter.write("import io.proleap.cobol.applicationcontext.CobolGrammarContextFactory;\n");
        pWriter.write("import io.proleap.cobol.preprocessor.CobolPreprocessor.CobolSourceFormatEnum;\n");
        pWriter.write("import io.proleap.cobol.runner.CobolParseTestRunner;\n");
        pWriter.write("import io.proleap.cobol.runner.impl.CobolParseTestRunnerImpl;\n");
        pWriter.write("import org.junit.Test;\n");
        pWriter.write("\n");
        pWriter.write("public class " + inputFilename + "Test {\n");
        pWriter.write("\n");
        pWriter.write("   @Test\n");
        pWriter.write("   public void test() throws Exception {\n");
        pWriter.write("      CobolGrammarContextFactory.configureDefaultApplicationContext();\n");
        pWriter.write("\n");
        pWriter.write("      final File inputFile = new File(\"" + cobolInputFileName + "\");\n");
        pWriter.write("      final CobolParseTestRunner runner = new CobolParseTestRunnerImpl();\n");
        pWriter.write("      runner.parseFile(inputFile, CobolSourceFormatEnum." + format + ");\n");
        pWriter.write("   }\n");
        pWriter.write("}");

        pWriter.flush();/*from  w  w w .j  a v  a  2  s.c o m*/
        pWriter.close();
    }
}

From source file:com.cdancy.artifactory.rest.util.ArtifactoryUtils.java

public static File getGradleFile(GAVCoordinates gavCoordinates, String fileName, String etag) {
    File gradleFile = new File(getGradleFilesDir(), gavCoordinates.group + "/" + gavCoordinates.artifact + "/"
            + gavCoordinates.version + "/" + etag + "/" + fileName);
    if (!gradleFile.getParentFile().exists()) {
        try {//w  w w  . j av a  2 s  .c om
            FileUtils.forceMkdir(gradleFile.getParentFile());
        } catch (Exception e) {
            Throwables.propagate(e);
        }
    }

    return gradleFile;
}

From source file:Main.java

private static void extractFileToPath(ZipFile nar, String targetPath, ZipEntry e, boolean ignorename,
        boolean strip) throws FileNotFoundException, IOException {
    File f = null;
    if (ignorename)
        f = new File(targetPath);
    else {/* w  w  w.  j  a  v  a2 s .  c  o  m*/

        f = new File(targetPath + "/" + (strip ? stripExtraLevel(e.getName()) : e.getName()));
    }
    File fP = f.getParentFile();
    if (fP != null && fP.exists() == false) {
        boolean s = fP.mkdirs();
        Log.d(TAG, "fp make" + s);
    }
    FileOutputStream os = new FileOutputStream(f);
    InputStream is = nar.getInputStream(e);
    copyFile(is, os);
}

From source file:com.dubture.symfony.core.util.UncompressUtils.java

/**
 * This will ensure the hierarchy of parent directories by creating
 * them if they do not exist./*from   w  ww. j av a2 s  .  c  om*/
 *
 * @param outputFile The output file for which hierarchy must exists
 */
private static void ensureDirectoryHierarchyExists(File outputFile) {
    if (!outputFile.getParentFile().exists()) {
        createDirectory(outputFile.getParentFile());
    }
}

From source file:info.magnolia.cms.beans.config.Bootstrapper.java

/**
 * Repositories appears to be empty and the <code>"magnolia.bootstrap.dir</code> directory is configured in
 * web.xml. Loops over all the repositories and try to load any xml file found in a subdirectory with the same name
 * of the repository. For example the <code>config</code> repository will be initialized using all the
 * <code>*.xml</code> files found in <code>"magnolia.bootstrap.dir</code><strong>/config</strong> directory.
 * @param bootdirs bootstrap dir//from w  w  w. j  av a2s. c o  m
 */
protected static void bootstrapRepositories(String[] bootdirs) {

    if (log.isInfoEnabled()) {
        log.info("-----------------------------------------------------------------"); //$NON-NLS-1$
        log.info("Trying to initialize repositories from:");
        for (int i = 0; i < bootdirs.length; i++) {
            log.info(bootdirs[i]);
        }
        log.info("-----------------------------------------------------------------"); //$NON-NLS-1$
    }

    MgnlContext.setInstance(MgnlContext.getSystemContext());

    Iterator repositoryNames = ContentRepository.getAllRepositoryNames();
    while (repositoryNames.hasNext()) {
        String repository = (String) repositoryNames.next();

        Set xmlfileset = new TreeSet(new Comparator() {

            // remove file with the same name in different dirs
            public int compare(Object file1obj, Object file2obj) {
                File file1 = (File) file1obj;
                File file2 = (File) file2obj;
                String fn1 = file1.getParentFile().getName() + '/' + file1.getName();
                String fn2 = file2.getParentFile().getName() + '/' + file2.getName();
                return fn1.compareTo(fn2);
            }
        });

        for (int j = 0; j < bootdirs.length; j++) {
            String bootdir = bootdirs[j];
            File xmldir = new File(bootdir, repository);
            if (!xmldir.exists() || !xmldir.isDirectory()) {
                continue;
            }

            File[] files = xmldir.listFiles(new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    return name.endsWith(DataTransporter.XML) || name.endsWith(DataTransporter.ZIP)
                            || name.endsWith(DataTransporter.GZ); //$NON-NLS-1$
                }
            });

            xmlfileset.addAll(Arrays.asList(files));

        }

        if (xmlfileset.isEmpty()) {
            log.info("No bootstrap files found in directory [{}], skipping...", repository); //$NON-NLS-1$
            continue;
        }

        log.info("Trying to import content from {} files into repository [{}]", //$NON-NLS-1$
                Integer.toString(xmlfileset.size()), repository);

        File[] files = (File[]) xmlfileset.toArray(new File[xmlfileset.size()]);
        Arrays.sort(files, new Comparator() {

            public int compare(Object file1, Object file2) {
                String name1 = StringUtils.substringBeforeLast(((File) file1).getName(), "."); //$NON-NLS-1$
                String name2 = StringUtils.substringBeforeLast(((File) file2).getName(), "."); //$NON-NLS-1$
                // a simple way to detect nested nodes
                return name1.length() - name2.length();
            }
        });

        try {
            for (int k = 0; k < files.length; k++) {

                File xmlfile = files[k];
                DataTransporter.executeBootstrapImport(xmlfile, repository);
            }

        } catch (IOException ioe) {
            log.error(ioe.getMessage(), ioe);
        } catch (OutOfMemoryError e) {
            int maxMem = (int) (Runtime.getRuntime().maxMemory() / 1024 / 1024);
            int needed = Math.max(256, maxMem + 128);
            log.error("Unable to complete bootstrapping: out of memory.\n" //$NON-NLS-1$
                    + "{} MB were not enough, try to increase the amount of memory available by adding the -Xmx{}m parameter to the server startup script.\n" //$NON-NLS-1$
                    + "You will need to completely remove the magnolia webapp before trying again", //$NON-NLS-1$
                    Integer.toString(maxMem), Integer.toString(needed));
            break;
        }

        log.info("Repository [{}] has been initialized.", repository); //$NON-NLS-1$

    }
}