⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileutils.java

📁 java ant的源码!非常值得看的源码
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
     * @return the local file system path for the file.     * @since Ant 1.6     */    public String fromURI(String uri) {        synchronized (cacheFromUriLock) {            if (uri.equals(cacheFromUriRequest)) {                return cacheFromUriResponse;            }            String path = Locator.fromURI(uri);            String ret = isAbsolutePath(path)                ? normalize(path).getAbsolutePath() : path;            cacheFromUriRequest = uri;            cacheFromUriResponse = ret;            return ret;        }    }    /**     * Compares two filenames.     *     * <p>Unlike java.io.File#equals this method will try to compare     * the absolute paths and &quot;normalize&quot; the filenames     * before comparing them.</p>     *     * @param f1 the file whose name is to be compared.     * @param f2 the other file whose name is to be compared.     *     * @return true if the file are for the same file.     *     * @since Ant 1.5.3     */    public boolean fileNameEquals(File f1, File f2) {        return normalize(f1.getAbsolutePath())            .equals(normalize(f2.getAbsolutePath()));    }    /**     * Renames a file, even if that involves crossing file system boundaries.     *     * <p>This will remove <code>to</code> (if it exists), ensure that     * <code>to</code>'s parent directory exists and move     * <code>from</code>, which involves deleting <code>from</code> as     * well.</p>     *     * @param from the file to move.     * @param to the new file name.     *     * @throws IOException if anything bad happens during this     * process.  Note that <code>to</code> may have been deleted     * already when this happens.     *     * @since Ant 1.6     */    public void rename(File from, File to) throws IOException {        if (to.exists() && !to.delete()) {            throw new IOException("Failed to delete " + to                                  + " while trying to rename " + from);        }        File parent = to.getParentFile();        if (parent != null && !parent.exists() && !parent.mkdirs()) {            throw new IOException("Failed to create directory " + parent                                  + " while trying to rename " + from);        }        if (!from.renameTo(to)) {            copyFile(from, to);            if (!from.delete()) {                throw new IOException("Failed to delete " + from                                      + " while trying to rename it.");            }        }    }    /**     * Get the granularity of file timestamps.     * The choice is made based on OS, which is incorrect--it should really be     * by filesystem. We do not have an easy way to probe for file systems,     * however, so this heuristic gives us a decent default.     * @return the difference, in milliseconds, which two file timestamps must have     * in order for the two files to be considered to have different timestamps.     */    public long getFileTimestampGranularity() {        if (onWin9x) {            return FAT_FILE_TIMESTAMP_GRANULARITY;        } else if (onWindows) {            return NTFS_FILE_TIMESTAMP_GRANULARITY;        } else if (onDos) {            return FAT_FILE_TIMESTAMP_GRANULARITY;        }        return UNIX_FILE_TIMESTAMP_GRANULARITY;    }    /**     * Returns true if the source is older than the dest.     * If the dest file does not exist, then the test returns false; it is     * implicitly not up do date.     * @param source source file (should be the older).     * @param dest dest file (should be the newer).     * @param granularity an offset added to the source time.     * @return true if the source is older than the dest after accounting     *              for granularity.     * @since Ant 1.6.3     */    public boolean isUpToDate(File source, File dest, long granularity) {        //do a check for the destination file existing        if (!dest.exists()) {            //if it does not, then the file is not up to date.            return false;        }        long sourceTime = source.lastModified();        long destTime = dest.lastModified();        return isUpToDate(sourceTime, destTime, granularity);    }    /**     * Returns true if the source is older than the dest.     * @param source source file (should be the older).     * @param dest dest file (should be the newer).     * @return true if the source is older than the dest, taking the granularity into account.     * @since Ant 1.6.3     */    public boolean isUpToDate(File source, File dest) {        return isUpToDate(source, dest, getFileTimestampGranularity());    }    /**     * Compare two timestamps for being up to date using     * the specified granularity.     *     * @param sourceTime timestamp of source file.     * @param destTime timestamp of dest file.     * @param granularity os/filesys granularity.     * @return true if the dest file is considered up to date.     */    public boolean isUpToDate(long sourceTime, long destTime, long granularity) {        if (destTime == -1) {            return false;        }        return destTime >= sourceTime + granularity;    }    /**     * Compare two timestamps for being up to date using the     * current granularity.     *     * @param sourceTime  timestamp of source file.     * @param destTime    timestamp of dest file.     * @return true if the dest file is considered up to date.     */    public boolean isUpToDate(long sourceTime, long destTime) {        return isUpToDate(sourceTime, destTime, getFileTimestampGranularity());    }    /**     * Close a Writer without throwing any exception if something went wrong.     * Do not attempt to close it if the argument is null.     * @param device output writer, can be null.     */    public static void close(Writer device) {        if (device != null) {            try {                device.close();            } catch (IOException ioex) {                //ignore            }        }    }    /**     * Close a stream without throwing any exception if something went wrong.     * Do not attempt to close it if the argument is null.     *     * @param device Reader, can be null.     */    public static void close(Reader device) {        if (device != null) {            try {                device.close();            } catch (IOException ioex) {                //ignore            }        }    }    /**     * Close a stream without throwing any exception if something went wrong.     * Do not attempt to close it if the argument is null.     *     * @param device stream, can be null.     */    public static void close(OutputStream device) {        if (device != null) {            try {                device.close();            } catch (IOException ioex) {                //ignore            }        }    }    /**     * Close a stream without throwing any exception if something went wrong.     * Do not attempt to close it if the argument is null.     *     * @param device stream, can be null.     */    public static void close(InputStream device) {        if (device != null) {            try {                device.close();            } catch (IOException ioex) {                //ignore            }        }    }    /**     * Delete the file with {@link File#delete()} if the argument is not null.     * Do nothing on a null argument.     * @param file file to delete.     */    public static void delete(File file) {        if (file != null) {            file.delete();        }    }    /**     * Calculates the relative path between two files.     * <p>     * Implementation note:<br/> This function my throw an IOException if an     * I/O error occurs because its use of the canonical pathname may require     * filesystem queries.     * </p>     *     * @param fromFile     *            the <code>File</code> to calculate the path from     * @param toFile     *            the <code>File</code> to calculate the path to     * @return the relative path between the files     * @throws Exception for undocumented reasons     * @see File#getCanonicalPath()     *     * @since Ant 1.7     */    public static String getRelativePath(        File fromFile,        File toFile    ) throws Exception {        String fromPath = fromFile.getCanonicalPath();        String toPath = toFile.getCanonicalPath();        // build the path stack info to compare        String[] fromPathStack = getPathStack(fromPath);        String[] toPathStack = getPathStack(toPath);        if (0 < toPathStack.length && 0 < fromPathStack.length) {            if (!fromPathStack[0].equals(toPathStack[0])) {                // not the same device (would be "" on Linux/Unix)                return getPath(Arrays.asList(toPathStack));            }        } else {            // no comparison possible            return getPath(Arrays.asList(toPathStack));        }        int minLength = Math                .min(fromPathStack.length, toPathStack.length);        int same = 1;        // get index of parts which are equal        for (; same < minLength; same++) {            if (!fromPathStack[same].equals(toPathStack[same])) {                break;            }        }        List relativePathStack = new ArrayList();        // if "from" part is longer, fill it up with ".."        // to reach path which is equal to both paths        for (int i = same; i < fromPathStack.length; i++) {            relativePathStack.add("..");        }        // fill it up path with parts which were not equal        for (int i = same; i < toPathStack.length; i++) {            relativePathStack.add(toPathStack[i]);        }        return getPath(relativePathStack);    }    /**     * Gets all names of the path as an array of <code>String</code>s.     *     * @param path     *            to get names from     * @return <code>String</code>s, never <code>null</code>     *     * @since Ant 1.7     */    public static String[] getPathStack(String path) {        String normalizedPath = path.replace(File.separatorChar, '/');        // since Java 1.4        //return normalizedPath.split("/");        // workaround for Java 1.2-1.3        Object[] tokens = StringUtils.split(normalizedPath, '/').toArray();        String[] rv = new String[tokens.length];        System.arraycopy(tokens, 0, rv, 0, tokens.length);        return rv;    }    /**     * Gets path from a <code>List</code> of <code>String</code>s.     *     * @param pathStack     *            <code>List</code> of <code>String</code>s to be concated     *            as a path.     * @return <code>String</code>, never <code>null</code>     *     * @since Ant 1.7     */    public static String getPath(List pathStack) {        // can safely use '/' because Windows understands '/' as separator        return getPath(pathStack, '/');    }    /**     * Gets path from a <code>List</code> of <code>String</code>s.     *     * @param pathStack     *            <code>List</code> of <code>String</code>s to be concated     *            as a path.     * @param separatorChar     *            <code>char</code> to be used as separator between names in     *            path     * @return <code>String</code>, never <code>null</code>     *     * @since Ant 1.7     */    public static String getPath(final List pathStack, final char separatorChar) {        final StringBuffer buffer = new StringBuffer();        final Iterator iter = pathStack.iterator();        if (iter.hasNext()) {            buffer.append(iter.next());        }        while (iter.hasNext()) {            buffer.append(separatorChar);            buffer.append(iter.next());        }        return buffer.toString();    }    /**     * Get the default encoding.     * This is done by opening an InputStreamReader on     * a dummy InputStream and getting the encoding.     * Could use System.getProperty("file.encoding"), but cannot     * see where this is documented.     * @return the default file encoding.     */    public String getDefaultEncoding() {        InputStreamReader is = new InputStreamReader(            new InputStream() {                public int read() {                    return -1;                }            });        try {            return is.getEncoding();        } finally {            close(is);        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -