Example usage for java.io File compareTo

List of usage examples for java.io File compareTo

Introduction

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

Prototype

public int compareTo(File pathname) 

Source Link

Document

Compares two abstract pathnames lexicographically.

Usage

From source file:Main.java

public static void main(String[] args) {
    File file1 = new File("C:/File/demo1.txt");
    File file2 = new File("C:/FileIO/demo1.txt");

    if (file1.compareTo(file2) == 0) {
        System.out.println("Both paths are same!");
    } else {//w  w  w. j  av  a  2s .c  om
        System.out.println("Paths are not same!");
    }
}

From source file:Main.java

public static void main(String[] args) {

    File f = new File("test.txt");
    File f1 = new File("File/test1.txt");

    // returns integer value
    int value = f.compareTo(f1);

    if (value == 0) {
        System.out.print(" = ");
    } else if (value > 0) {
        System.out.print(" >  ");
    } else {// ww  w  . j  av a 2 s.c  o m
        System.out.print(" < ");
    }
    System.out.print("Value returned: " + value);

}

From source file:net.ftb.util.FileUtils.java

public static List<File> listDirs(File path) {
    List<File> ret = Lists.newArrayList();
    if (path.exists())
        listDirs(path, ret);/*from  ww  w  .  j  a v  a 2s  .  c o  m*/
    Collections.sort(ret, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o2.compareTo(o1);
        }
    });
    return ret;
}

From source file:net.ftb.util.FTBFileUtils.java

public static List<File> listDirs(File path) {
    List<File> ret = Lists.newArrayList();
    if (path.exists()) {
        listDirs(path, ret);// w w w.  ja  va  2s .  c om
    }
    Collections.sort(ret, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o2.compareTo(o1);
        }
    });
    return ret;
}

From source file:dk.netarkivet.harvester.harvesting.controller.AbstractJMXHeritrixController.java

/**
 * Change an environment to be suitable for running Heritrix.
 *
 * At the moment, this involves the following:
 *
 * Prepend the Jar files from the lib/heritrix/lib dir to the classpath.
 * Make sure the Heritrix jar file is at the front.
 *
 * @param environment//from  w  ww  .j  av  a2s .  c o m
 *            The environment from a process builder
 * @throws IOFailure
 *             If a Heritrix jarfile is not found.
 */
private static void updateEnvironment(Map<String, String> environment) {
    List<String> classPathParts = SystemUtils.getCurrentClasspath();
    File heritrixLibDir = new File("lib/heritrix/lib");
    File[] jars = heritrixLibDir.listFiles(new FilenameFilter() {
        public boolean accept(File file, String string) {
            return string.endsWith(".jar");
        }
    });
    // Reverse sort the file list in order to add in alphabetical order
    // before the basic jars.
    Arrays.sort(jars, new Comparator<File>() {
        public int compare(File file, File file1) {
            return file1.compareTo(file);
        }
    });
    String heritixJar = null;
    for (File lib : jars) {
        final String jarPath = new File(heritrixLibDir, lib.getName()).getAbsolutePath();
        if (lib.getName().startsWith("heritrix-")) {
            // Heritrix should be at the very head, as it redefines some
            // of the functions in its dependencies (!). Thus, we have to
            // save it for later insertion at the head.
            heritixJar = jarPath;
        } else {
            classPathParts.add(0, jarPath);
        }
    }
    if (heritixJar != null) {
        classPathParts.add(0, heritixJar);
    } else {
        throw new IOFailure("Heritrix jar file not found");
    }
    environment.put("CLASSPATH", StringUtils.conjoin(FILE_PATH_SEPARATOR, classPathParts));
}

From source file:org.orekit.data.DirectoryCrawler.java

/** Feed a data file loader by browsing a directory hierarchy.
 * @param supported pattern for file names supported by the visitor
 * @param visitor data file visitor to feed
 * @param directory current directory//from  w  w w .j  a v a2s. c  o  m
 * @exception OrekitException if some data is missing, duplicated
 * or can't be read
 * @return true if something has been loaded
 * @exception IOException if data cannot be read
 * @exception ParseException if data cannot be read
 */
private boolean feed(final Pattern supported, final DataLoader visitor, final File directory)
        throws OrekitException, IOException, ParseException {

    // search in current directory
    final File[] list = directory.listFiles();
    Arrays.sort(list, new Comparator<File>() {
        @Override
        public int compare(final File o1, final File o2) {
            return o1.compareTo(o2);
        }
    });

    OrekitException delayedException = null;
    boolean loaded = false;
    for (int i = 0; i < list.length; ++i) {
        try {
            if (visitor.stillAcceptsData()) {
                if (list[i].isDirectory()) {

                    // recurse in the sub-directory
                    loaded = feed(supported, visitor, list[i]) || loaded;

                } else if (ZIP_ARCHIVE_PATTERN.matcher(list[i].getName()).matches()) {

                    // browse inside the zip/jar file
                    final DataProvider zipProvider = new ZipJarCrawler(list[i]);
                    loaded = zipProvider.feed(supported, visitor) || loaded;

                } else {

                    // remove suffix from gzip files
                    final Matcher gzipMatcher = GZIP_FILE_PATTERN.matcher(list[i].getName());
                    final String baseName = gzipMatcher.matches() ? gzipMatcher.group(1) : list[i].getName();

                    if (supported.matcher(baseName).matches()) {

                        // visit the current file
                        InputStream input = new FileInputStream(list[i]);
                        if (gzipMatcher.matches()) {
                            input = new GZIPInputStream(input);
                        }
                        visitor.loadData(input, list[i].getPath());
                        input.close();
                        loaded = true;

                    }

                }
            }
        } catch (OrekitException oe) {
            delayedException = oe;
        }

    }

    if (!loaded && delayedException != null) {
        throw delayedException;
    }

    return loaded;

}

From source file:edu.unc.lib.dl.ingest.sip.METSPackageFileValidator.java

/**
 * Checks that there are as many files packaged as there are non-staged file references. Computes and compares the
 * MD5 digest of packaged files that have a checksum in METS. Checks access to all files referenced in staging
 * locations.//  w  w  w . jav  a2s.com
 *
 * @param mets
 * @param metsPack
 * @param aip
 * @throws IngestException
 */
@SuppressWarnings("unchecked")
public void validateFiles(Document mets, METSPackageSIP metsPack) throws IngestException {
    StringBuffer errors = new StringBuffer();
    List<File> manifestFiles = new ArrayList<File>();
    List<String> missingFiles = new ArrayList<String>();
    List<String> badChecksumFiles = new ArrayList<String>();

    // find missing or corrupt files listed in manifest
    try {
        for (Element fileEl : (List<Element>) allFilesXpath.selectNodes(mets)) {
            String href = null;
            try {
                href = fileEl.getChild("FLocat", JDOMNamespaceUtil.METS_NS).getAttributeValue("href",
                        JDOMNamespaceUtil.XLINK_NS);
                URI uri = new URI(href);
                if (uri.getScheme() != null && !uri.getScheme().contains("file")) {
                    continue;
                }
            } catch (URISyntaxException e) {
                errors.append("Cannot parse file location: " + e.getLocalizedMessage() + " (" + href + ")");
                missingFiles.add(href);
                continue;
            } catch (NullPointerException e) {
                errors.append("A file location is missing for file ID: " + fileEl.getAttributeValue("ID"));
                continue;
            }
            File file = null;
            // locate the file and check that it exists
            try {
                log.debug("Looking in SIP");
                file = metsPack.getFileForLocator(href);
                file.equals(file);
                manifestFiles.add(file);
                log.debug("FILE IS IN METSPackage: " + file.getPath());
                if (file == null || !file.exists()) {
                    missingFiles.add(href);
                    continue;
                }
            } catch (IOException e) {
                log.debug(e);
                missingFiles.add(href);
                errors.append(e.getMessage());
            }

            String checksum = fileEl.getAttributeValue("CHECKSUM");
            if (checksum != null) {
                log.debug("found a checksum in METS");
                Checksum checker = new Checksum();
                try {
                    String sum = checker.getChecksum(file);
                    if (!sum.equals(checksum.toLowerCase())) {
                        log.debug("Checksum failed for file: " + href + " (METS says " + checksum
                                + ", but we got " + sum + ")");
                        badChecksumFiles.add(href);
                    }
                    log.debug("METS manifest checksum was verified for file: " + href);
                } catch (IOException e) {
                    throw new IngestException("Checksum failed to find file: " + href);
                }
            }
        }
    } catch (JDOMException e1) {
        throw new Error("Unexpected JDOM Exception", e1);
    }

    // TODO: account for local (not inline xmlData) MODS files
    // see if there are extra files in the SIP
    List<String> extraFiles = new ArrayList<String>();

    if (metsPack.getSIPDataDir() != null) {
        int zipPathLength = 0;
        try {
            zipPathLength = metsPack.getSIPDataDir().getCanonicalPath().length();

            for (File received : metsPack.getDataFiles()) {
                if (!manifestFiles.contains(received) && received.compareTo(metsPack.getMetsFile()) != 0) {
                    extraFiles.add("file://" + received.getCanonicalPath().substring(zipPathLength));
                }
            }
        } catch (IOException e) {
            throw new Error("Unexpected IO Exception trying to get path of a known file.", e);
        }
    }
    if (missingFiles.size() > 0 || badChecksumFiles.size() > 0 || extraFiles.size() > 0) {
        // We have an error here...
        String msg = "The files submitted do not match those listed in the METS manifest.";
        FilesDoNotMatchManifestException e = new FilesDoNotMatchManifestException(msg);
        e.setBadChecksumFiles(badChecksumFiles);
        e.setExtraFiles(extraFiles);
        e.setMissingFiles(missingFiles);
        throw e;
    }
}

From source file:org.apache.hawq.pxf.plugins.json.parser.PartitionedJsonParserSeekTest.java

public void runTest(final File jsonDir) throws IOException {

    File jsonFile = new File(jsonDir, "input.json");
    InputStream jsonInputStream = new FileInputStream(jsonFile);

    try {//w ww  .ja  v a 2 s  .  co m
        seekToStart(jsonInputStream);
        PartitionedJsonParser parser = new PartitionedJsonParser(jsonInputStream);

        File[] jsonOjbectFiles = jsonFile.getParentFile().listFiles(new FilenameFilter() {
            public boolean accept(File file, String s) {
                return s.contains("expected");
            }
        });

        Arrays.sort(jsonOjbectFiles, new Comparator<File>() {
            public int compare(File file, File file1) {
                return file.compareTo(file1);
            }
        });

        if (jsonOjbectFiles == null || jsonOjbectFiles.length == 0) {
            String result = parser.nextObjectContainingMember("name");
            assertNull("File " + jsonFile.getAbsolutePath() + " got result '" + result + "'", result);
            LOG.info("File " + jsonFile.getAbsolutePath() + " passed");
        } else {
            for (File jsonObjectFile : jsonOjbectFiles) {
                String expected = trimWhitespaces(FileUtils.readFileToString(jsonObjectFile));
                String result = parser.nextObjectContainingMember("name");
                assertNotNull(jsonFile.getAbsolutePath() + "/" + jsonObjectFile.getName(), result);
                assertEquals(jsonFile.getAbsolutePath() + "/" + jsonObjectFile.getName(), expected,
                        trimWhitespaces(result));
                LOG.info("File " + jsonFile.getAbsolutePath() + "/" + jsonObjectFile.getName() + " passed");
            }
        }

    } finally {
        IOUtils.closeQuietly(jsonInputStream);
    }
}

From source file:org.jumpmind.symmetric.ClientSymmetricEngine.java

public List<File> listSnapshots() {
    File snapshotsDir = SnapshotUtil.getSnapshotDirectory(this);
    List<File> files = new ArrayList<File>(FileUtils.listFiles(snapshotsDir, new String[] { "zip" }, false));
    Collections.sort(files, new Comparator<File>() {
        public int compare(File o1, File o2) {
            return -o1.compareTo(o2);
        }//from   ww  w. j  a v  a  2  s  .  c  o m
    });
    return files;
}