Example usage for java.io File equals

List of usage examples for java.io File equals

Introduction

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

Prototype

public boolean equals(Object obj) 

Source Link

Document

Tests this abstract pathname for equality with the given object.

Usage

From source file:it.geosolutions.tools.compress.file.Extract.java

public static File extract(final File inFile, File destination, final boolean remove_source) throws Exception {

    if (inFile == null) {
        throw new IllegalArgumentException("Cannot open null file.");
    } else if (!inFile.exists()) {
        throw new FileNotFoundException(
                "The path does not match to an existent file into the filesystem: " + inFile);
    }//from ww w . j a v  a  2  s . com
    if (destination == null || !destination.isDirectory() || !destination.canWrite()) {
        throw new IllegalArgumentException(
                "Extract: cannot write to a null or not writeable destination folder: " + destination);
    }

    // the new file-dir
    File end_file = null;

    final Matcher m = match(inFile.getName());
    if (m != null) {
        switch (getEnumType(inFile, true)) {
        case TAR:
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Input file is a tar file: " + inFile);
                LOGGER.info("Untarring...");
            }
            end_file = new File(destination, getName(m));
            if (end_file.equals(inFile)) {
                // rename inFile
                File tarFile = new File(inFile.getParent(), inFile.getName() + ".tar");
                FileUtils.moveFile(inFile, tarFile);
                TarReader.readTar(tarFile, end_file);
            } else {
                TarReader.readTar(inFile, end_file);
            }

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("tar extracted to " + end_file);
            }

            if (remove_source) {
                inFile.delete();
            }

            break;

        case BZIP2:
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a BZ2 compressed file.");

            // Output filename
            end_file = new File(destination, getName(m));

            // uncompress BZ2 to the tar file
            Extractor.extractBz2(inFile, end_file);

            if (remove_source) {
                inFile.delete();
            }

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("BZ2 uncompressed to " + end_file.getAbsolutePath());
            }

            end_file = extract(end_file, destination, true);
            break;
        case GZIP:
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a Gz compressed file.");

            // Output filename
            end_file = new File(destination, getName(m));

            // uncompress BZ2 to the tar file
            Extractor.extractGzip(inFile, end_file);

            if (remove_source)
                inFile.delete();

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("GZ extracted to " + end_file);
            }

            // recursion
            end_file = extract(end_file, destination, true);

            break;
        case ZIP:

            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a ZIP compressed file. UnZipping...");

            // preparing path to extract to
            end_file = new File(destination, getName(m));

            // run the unzip method
            Extractor.unZip(inFile, end_file);

            if (remove_source)
                inFile.delete();

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Zip file uncompressed to " + end_file);
            }

            // recursion
            end_file = extract(end_file, destination, remove_source);
            break;
        case NORMAL:

            end_file = inFile;

            if (LOGGER.isInfoEnabled())
                LOGGER.info("Working on a not compressed file.");
            break;
        default:
            throw new Exception("format file still not supported! Please try using bz2, gzip or zip");
        } // switch
    } // if match
    else {
        throw new Exception("File do not match regular expression");
    }

    /**
     * returning output file name
     */
    return end_file;
}

From source file:org.pentaho.reporting.libraries.base.util.ObjectUtilities.java

/**
 * Performs a comparison on two file objects to determine if they refer to the same file. The
 * <code>File.equals()</code> method requires that the files refer to the same file in the same way (relative vs.
 * absolute)./*from w  w w  . j a v a  2s.c  o m*/
 *
 * @param file1 the first file (<code>null</code> permitted).
 * @param file2 the second file (<code>null</code> permitted).
 * @return <code>true</code> if the files refer to the same file, <code>false</code> otherwise
 */
public static boolean equals(final File file1, final File file2) {
    if (file1 == file2) {
        return true;
    }
    if (file1 != null && file2 != null) {
        try {
            return file1.getCanonicalFile().equals(file2.getCanonicalFile());
        } catch (IOException ioe) {
            // There was an error accessing the filesystem
            return file1.equals(file2);
        }
    }
    return false;
}

From source file:org.openflexo.toolbox.FileUtils.java

public static boolean isFileContainedIn(File aFile, File ancestorFile) {
    File current = aFile;
    while (current != null) {
        if (current.equals(ancestorFile)) {
            return true;
        }// w  w  w.j a v a 2 s  . c  om
        current = current.getParentFile();
    }
    return false;
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

private static String getAbsFileName(String baseDir, File realFileName) {
    File real = realFileName;
    File base = new File(baseDir);
    String ret = real.getName();//  ww w  .  j a va 2 s. c  o m
    while (true) {
        real = real.getParentFile();
        if (real == null) {
            break;
        }
        if (real.equals(base)) {
            break;
        } else {
            ret = real.getName() + "/" + ret;
        }
    }
    return ret;
}

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

public static void createStorageLocations() {
    File cacheDir = new File(OSUtils.getCacheStorageLocation());
    File dynamicDir = new File(OSUtils.getDynamicStorageLocation());

    if (!cacheDir.exists()) {
        cacheDir.mkdirs();/*from   w w w .j av a 2s  .co  m*/

        if (dynamicDir.exists() && !cacheDir.equals(dynamicDir)) {
            // Migrate cached archives from the user's roaming profile to their local cache

            Logger.logInfo("Migrating cached Maps from Roaming to Local storage");
            FTBFileUtils.move(new File(dynamicDir, "Maps"), new File(cacheDir, "Maps"));

            Logger.logInfo("Migrating cached Modpacks from Roaming to Local storage");
            FTBFileUtils.move(new File(dynamicDir, "ModPacks"), new File(cacheDir, "ModPacks"));

            Logger.logInfo("Migrating cached Texturepacks from Roaming to Local storage");
            FTBFileUtils.move(new File(dynamicDir, "TexturePacks"), new File(cacheDir, "TexturePacks"));

            Logger.logInfo("Migration complete.");
        }
    }

    if (!dynamicDir.exists()) {
        dynamicDir.mkdirs();
    }

    if (getCurrentOS() == OS.WINDOWS) {
        File oldLoginData = new File(dynamicDir, "logindata");
        File newLoginData = new File(cacheDir, "logindata");
        try {
            if (oldLoginData.exists()
                    && !oldLoginData.getCanonicalPath().equals(newLoginData.getCanonicalPath())) {
                newLoginData.delete();
            }
        } catch (Exception e) {
            Logger.logError("Error deleting login data", e);
        }
    }
}

From source file:org.omegat.util.FileUtil.java

private static Map<File, File> copyFilesTo(File destination, File[] toCopy, File root) throws IOException {
    Map<File, File> collisions = new LinkedHashMap<File, File>();
    for (File file : toCopy) {
        if (destination.getPath().startsWith(file.getPath())) {
            // Trying to copy something into its own subtree
            continue;
        }//from w  ww  .  j  ava  2s .  c  o  m
        File thisRoot = root == null ? file.getParentFile() : root;
        String filePath = file.getPath();
        String relPath = filePath.substring(thisRoot.getPath().length(), filePath.length());
        File dest = new File(destination, relPath);
        if (file.equals(dest)) {
            // Trying to copy file to itself. Skip.
            continue;
        }
        if (dest.exists()) {
            collisions.put(file, dest);
            continue;
        }
        if (file.isDirectory()) {
            copyFilesTo(destination, file.listFiles(), thisRoot);
        } else {
            FileUtils.copyFile(file, dest);
        }
    }
    return collisions;
}

From source file:org.lockss.util.PlatformUtil.java

public static String longestRootFile(File file) {
    String longestRoot = null;//from w  ww . j  av a2  s  .  co  m

    for (File root : FILE_ROOTS) {
        File parent = file.getParentFile();
        while (parent != null) {
            if (root.equals(parent)) {
                if (longestRoot == null || longestRoot.length() < root.getPath().length()) {
                    longestRoot = root.getPath();
                }
            }
            parent = parent.getParentFile();
        }
    }
    return longestRoot;
}

From source file:org.opennms.ng.services.snmpconfig.SnmpPeerFactory.java

/**
 * <p>setFile</p>/*from   ww  w  .  ja  v a  2 s. c  o  m*/
 *
 * @param configFile a {@link java.io.File} object.
 */
public static void setFile(final File configFile) {
    SnmpPeerFactory.getWriteLock().lock();
    try {
        final File oldFile = m_configFile;
        m_configFile = configFile;

        // if the file changed then we need to reload the config
        if (oldFile == null || m_configFile == null || !oldFile.equals(m_configFile)) {
            m_singleton = null;
            m_loaded = false;
        }
    } finally {
        SnmpPeerFactory.getWriteLock().unlock();
    }
}

From source file:org.jets3t.service.utils.ObjectUtils.java

/**
 * Prepares a file for upload to a named object in S3, potentially transforming it if
 * zipping or encryption is requested./*from   w  w  w .j a va2 s.co  m*/
 * <p>
 * The file will have the following metadata items added:
 * <ul>
 * <li>{@link Constants#METADATA_JETS3T_LOCAL_FILE_DATE}: The local file's last modified date
 *     in ISO 8601 format</li>
 * <li><tt>Content-Type</tt> : A content type guessed from the file's extension, or
 *     {@link Mimetypes#MIMETYPE_BINARY_OCTET_STREAM} if the file is a directory</li>
 * <li><tt>Content-Length</tt> : The size of the file</li>
 * <li><tt>MD5-Hash</tt> : An MD5 hash of the file's data</li>
 * <li>{@link StorageObject#METADATA_HEADER_ORIGINAL_HASH_MD5}: An MD5 hash of the
 *     original file's data (added if gzipping or encryption is applied)</li>
 * </ul>
 *
 * @param objectKey
 * the object key name to use in S3
 * @param dataFile
 * the file to prepare for upload.
 * @param encryptionUtil
 * if this variable is null no encryption will be applied, otherwise the provided
 * encryption utility object will be used to encrypt the file's data.
 * @param gzipFile
 * if true the file will be Gzipped.
 * @param progressWatcher
 * watcher to monitor progress of file transformation and hash generation.
 *
 * @return
 * an S3Object representing the file, or a transformed copy of the file, complete with
 * all JetS3t-specific metadata items set and ready for upload to S3.
 *
 * @throws Exception
 * exceptions could include IO failures, gzipping and encryption failures.
 */
public static SS3Object createObjectForUpload(String objectKey, File dataFile, EncryptionUtil encryptionUtil,
        boolean gzipFile, BytesProgressWatcher progressWatcher) throws Exception {
    SS3Object s3Object = new SS3Object(objectKey);

    // Set object explicitly to private access by default.
    s3Object.setAcl(S3AccessControlList.REST_CANNED_PRIVATE);

    s3Object.addMetadata(Constants.METADATA_JETS3T_LOCAL_FILE_DATE,
            ServiceUtils.formatIso8601Date(new Date(dataFile.lastModified())));

    if (dataFile.isDirectory()) {
        s3Object.setContentLength(0);
        s3Object.setContentType(Mimetypes.MIMETYPE_BINARY_OCTET_STREAM);
    } else {
        s3Object.setContentType(Mimetypes.getInstance().getMimetype(dataFile));
        File uploadFile = transformUploadFile(dataFile, s3Object, encryptionUtil, gzipFile, progressWatcher);
        s3Object.setContentLength(uploadFile.length());
        s3Object.setDataInputFile(uploadFile);

        // Compute the upload file's MD5 hash.
        InputStream inputStream = new BufferedInputStream(new FileInputStream(uploadFile));
        if (progressWatcher != null) {
            inputStream = new ProgressMonitoredInputStream(inputStream, progressWatcher);
        }
        s3Object.setMd5Hash(ServiceUtils.computeMD5Hash(inputStream));

        if (!uploadFile.equals(dataFile)) {
            // Compute the MD5 hash of the *original* file, if upload file has been altered
            // through encryption or gzipping.
            inputStream = new BufferedInputStream(new FileInputStream(dataFile));
            if (progressWatcher != null) {
                inputStream = new ProgressMonitoredInputStream(inputStream, progressWatcher);
            }

            s3Object.addMetadata(SS3Object.METADATA_HEADER_ORIGINAL_HASH_MD5,
                    ServiceUtils.toBase64(ServiceUtils.computeMD5Hash(inputStream)));
        }
    }
    return s3Object;
}

From source file:org.openflexo.toolbox.FileUtils.java

/**
 * @param file/*from   ww  w .j  a v a  2s  .  com*/
 * @param wd
 * @return
 * @throws IOException
 */
public static String makeFilePathRelativeToDir(File file, File dir) throws IOException {
    file = file.getCanonicalFile();
    dir = dir.getCanonicalFile();
    String d = dir.getCanonicalPath().replace('\\', '/');
    String f = file.getCanonicalPath().replace('\\', '/');
    int i = 0;
    while (i < d.length() && i < f.length() && d.charAt(i) == f.charAt(i)) {
        i++;
    }
    String common = d.substring(0, i);
    if (!new File(common).exists()) {
        if (common.indexOf('/') > -1) {
            common = common.substring(0, common.lastIndexOf('/') + 1);
        }
        if (!new File(common).exists()) {
            System.err.println("WARNING\tNothing in common between\n" + file.getAbsolutePath() + " and\n"
                    + dir.getAbsolutePath());
            return file.getAbsolutePath();
        }
    }
    File commonFather = new File(common);
    File parentDir = dir;
    StringBuilder sb = new StringBuilder();
    while (parentDir != null && !commonFather.equals(parentDir)) {
        sb.append("../");
        parentDir = parentDir.getParentFile();
    }
    sb.append(f.substring(common.length()));
    if (sb.charAt(0) == '/') {
        return sb.substring(1);
    }
    return sb.toString();
}