您当前的位置: 首页 >  Java

wespten

暂无认证

  • 1浏览

    0关注

    899博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

深入学习java源码之File类

wespten 发布时间:2019-08-29 08:03:12 ,浏览量:1

File 类的常用方法

  ①、创建方法

    1.boolean createNewFile() 不存在返回true 存在返回false     2.boolean mkdir() 创建目录,如果上一级目录不存在,则会创建失败     3.boolean mkdirs() 创建多级目录,如果上一级目录不存在也会自动创建

  ②、删除方法

    1.boolean delete() 删除文件或目录,如果表示目录,则目录下必须为空才能删除     2.boolean deleteOnExit() 文件使用完成后删除

  ③、判断方法

    1.boolean canExecute()判断文件是否可执行     2.boolean canRead()判断文件是否可读     3.boolean canWrite() 判断文件是否可写     4.boolean exists() 判断文件或目录是否存在     5.boolean isDirectory()  判断此路径是否为一个目录     6.boolean isFile()  判断是否为一个文件     7.boolean isHidden()  判断是否为隐藏文件     8.boolean isAbsolute()判断是否是绝对路径 文件不存在也能判断

   ④、获取方法

    1.String getName() 获取此路径表示的文件或目录名称     2.String getPath() 将此路径名转换为路径名字符串     3.String getAbsolutePath() 返回此抽象路径名的绝对形式     4.String getParent()//如果没有父目录返回null     5.long lastModified()//获取最后一次修改的时间     6.long length() 返回由此抽象路径名表示的文件的长度。     7.boolean renameTo(File f) 重命名由此抽象路径名表示的文件。     8.File[] liseRoots()//获取机器盘符     9.String[] list()  返回一个字符串数组,命名由此抽象路径名表示的目录中的文件和目录。     10.String[] list(FilenameFilter filter) 返回一个字符串数组,命名由此抽象路径名表示的目录中满足指定过滤器的文件和目录。

package java.io;

import java.net.URI;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.ArrayList;
import java.security.AccessController;
import java.security.SecureRandom;
import java.nio.file.Path;
import java.nio.file.FileSystems;
import sun.security.action.GetPropertyAction;



public class File
    implements Serializable, Comparable
{

    /**
     * The FileSystem object representing the platform's local file system.
     */
    private static final FileSystem fs = DefaultFileSystem.getFileSystem();

    /**
     * This abstract pathname's normalized pathname string. A normalized
     * pathname string uses the default name-separator character and does not
     * contain any duplicate or redundant separators.
     *
     * @serial
     */
    private final String path;

    /**
     * Enum type that indicates the status of a file path.
     */
    private static enum PathStatus { INVALID, CHECKED };

    /**
     * The flag indicating whether the file path is invalid.
     */
    private transient PathStatus status = null;


    final boolean isInvalid() {
        if (status == null) {
            status = (this.path.indexOf('\u0000') < 0) ? PathStatus.CHECKED
                                                       : PathStatus.INVALID;
        }
        return status == PathStatus.INVALID;
    }

    /**
     * The length of this abstract pathname's prefix, or zero if it has no
     * prefix.
     */
    private final transient int prefixLength;

    /**
     * Returns the length of this abstract pathname's prefix.
     * For use by FileSystem classes.
     */
    int getPrefixLength() {
        return prefixLength;
    }


    public static final char separatorChar = fs.getSeparator();

    /**
     * The system-dependent default name-separator character, represented as a
     * string for convenience.  This string contains a single character, namely
     * {@link #separatorChar}.
     */
    public static final String separator = "" + separatorChar;

    public static final char pathSeparatorChar = fs.getPathSeparator();

    public static final String pathSeparator = "" + pathSeparatorChar;


    /* -- Constructors -- */

    /**
     * Internal constructor for already-normalized pathname strings.
     */
    private File(String pathname, int prefixLength) {
        this.path = pathname;
        this.prefixLength = prefixLength;
    }

    /**
     * Internal constructor for already-normalized pathname strings.
     * The parameter order is used to disambiguate this method from the
     * public(File, String) constructor.
     */
    private File(String child, File parent) {
        assert parent.path != null;
        assert (!parent.path.equals(""));
        this.path = fs.resolve(parent.path, child);
        this.prefixLength = parent.prefixLength;
    }

    /**
     * Creates a new File instance by converting the given
     * pathname string into an abstract pathname.  If the given string is
     * the empty string, then the result is the empty abstract pathname.
     *
     * @param   pathname  A pathname string
     * @throws  NullPointerException
     *          If the pathname argument is null
     */
    public File(String pathname) {
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }


    public File(String parent, String child) {
        if (child == null) {
            throw new NullPointerException();
        }
        if (parent != null) {
            if (parent.equals("")) {
                this.path = fs.resolve(fs.getDefaultParent(),
                                       fs.normalize(child));
            } else {
                this.path = fs.resolve(fs.normalize(parent),
                                       fs.normalize(child));
            }
        } else {
            this.path = fs.normalize(child);
        }
        this.prefixLength = fs.prefixLength(this.path);
    }

    public File(File parent, String child) {
        if (child == null) {
            throw new NullPointerException();
        }
        if (parent != null) {
            if (parent.path.equals("")) {
                this.path = fs.resolve(fs.getDefaultParent(),
                                       fs.normalize(child));
            } else {
                this.path = fs.resolve(parent.path,
                                       fs.normalize(child));
            }
        } else {
            this.path = fs.normalize(child);
        }
        this.prefixLength = fs.prefixLength(this.path);
    }

    public File(URI uri) {

        // Check our many preconditions
        if (!uri.isAbsolute())
            throw new IllegalArgumentException("URI is not absolute");
        if (uri.isOpaque())
            throw new IllegalArgumentException("URI is not hierarchical");
        String scheme = uri.getScheme();
        if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
            throw new IllegalArgumentException("URI scheme is not \"file\"");
        if (uri.getAuthority() != null)
            throw new IllegalArgumentException("URI has an authority component");
        if (uri.getFragment() != null)
            throw new IllegalArgumentException("URI has a fragment component");
        if (uri.getQuery() != null)
            throw new IllegalArgumentException("URI has a query component");
        String p = uri.getPath();
        if (p.equals(""))
            throw new IllegalArgumentException("URI path component is empty");

        // Okay, now initialize
        p = fs.fromURIPath(p);
        if (File.separatorChar != '/')
            p = p.replace('/', File.separatorChar);
        this.path = fs.normalize(p);
        this.prefixLength = fs.prefixLength(this.path);
    }


    /* -- Path-component accessors -- */

    /**
     * Returns the name of the file or directory denoted by this abstract
     * pathname.  This is just the last name in the pathname's name
     * sequence.  If the pathname's name sequence is empty, then the empty
     * string is returned.
     *
     * @return  The name of the file or directory denoted by this abstract
     *          pathname, or the empty string if this pathname's name sequence
     *          is empty
     */
    public String getName() {
        int index = path.lastIndexOf(separatorChar);
        if (index < prefixLength) return path.substring(prefixLength);
        return path.substring(index + 1);
    }

    /**
     * Returns the pathname string of this abstract pathname's parent, or
     * null if this pathname does not name a parent directory.
     *
     * 

The parent of an abstract pathname consists of the * pathname's prefix, if any, and each name in the pathname's name * sequence except for the last. If the name sequence is empty then * the pathname does not name a parent directory. * * @return The pathname string of the parent directory named by this * abstract pathname, or null if this pathname * does not name a parent */ public String getParent() { int index = path.lastIndexOf(separatorChar); if (index < prefixLength) { if ((prefixLength > 0) && (path.length() > prefixLength)) return path.substring(0, prefixLength); return null; } return path.substring(0, index); } public File getParentFile() { String p = this.getParent(); if (p == null) return null; return new File(p, this.prefixLength); } /** * Converts this abstract pathname into a pathname string. The resulting * string uses the {@link #separator default name-separator character} to * separate the names in the name sequence. * * @return The string form of this abstract pathname */ public String getPath() { return path; } public boolean isAbsolute() { return fs.isAbsolute(this); } public String getAbsolutePath() { return fs.resolve(this); } public File getAbsoluteFile() { String absPath = getAbsolutePath(); return new File(absPath, fs.prefixLength(absPath)); } public String getCanonicalPath() throws IOException { if (isInvalid()) { throw new IOException("Invalid file path"); } return fs.canonicalize(fs.resolve(this)); } public File getCanonicalFile() throws IOException { String canonPath = getCanonicalPath(); return new File(canonPath, fs.prefixLength(canonPath)); } private static String slashify(String path, boolean isDirectory) { String p = path; if (File.separatorChar != '/') p = p.replace(File.separatorChar, '/'); if (!p.startsWith("/")) p = "/" + p; if (!p.endsWith("/") && isDirectory) p = p + "/"; return p; } @Deprecated public URL toURL() throws MalformedURLException { if (isInvalid()) { throw new MalformedURLException("Invalid file path"); } return new URL("file", "", slashify(getAbsolutePath(), isDirectory())); } public URI toURI() { try { File f = getAbsoluteFile(); String sp = slashify(f.getPath(), f.isDirectory()); if (sp.startsWith("//")) sp = "//" + sp; return new URI("file", null, sp, null); } catch (URISyntaxException x) { throw new Error(x); // Can't happen } } public boolean canRead() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return fs.checkAccess(this, FileSystem.ACCESS_READ); } public boolean canWrite() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.checkAccess(this, FileSystem.ACCESS_WRITE); } public boolean exists() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0); } public boolean isDirectory() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY) != 0); } public boolean isFile() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0); } public boolean isHidden() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return false; } return ((fs.getBooleanAttributes(this) & FileSystem.BA_HIDDEN) != 0); } public long lastModified() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getLastModifiedTime(this); } public long length() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getLength(this); } /* -- File operations -- */ public boolean createNewFile() throws IOException { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkWrite(path); if (isInvalid()) { throw new IOException("Invalid file path"); } return fs.createFileExclusively(path); } public boolean delete() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkDelete(path); } if (isInvalid()) { return false; } return fs.delete(this); } public void deleteOnExit() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkDelete(path); } if (isInvalid()) { return; } DeleteOnExitHook.add(path); } public String[] list() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkRead(path); } if (isInvalid()) { return null; } return fs.list(this); } public String[] list(FilenameFilter filter) { String names[] = list(); if ((names == null) || (filter == null)) { return names; } List v = new ArrayList(); for (int i = 0 ; i < names.length ; i++) { if (filter.accept(this, names[i])) { v.add(names[i]); } } return v.toArray(new String[v.size()]); } public File[] listFiles() { String[] ss = list(); if (ss == null) return null; int n = ss.length; File[] fs = new File[n]; for (int i = 0; i < n; i++) { fs[i] = new File(ss[i], this); } return fs; } public File[] listFiles(FilenameFilter filter) { String ss[] = list(); if (ss == null) return null; ArrayList files = new ArrayList(); for (String s : ss) if ((filter == null) || filter.accept(this, s)) files.add(new File(s, this)); return files.toArray(new File[files.size()]); } /** * Returns an array of abstract pathnames denoting the files and * directories in the directory denoted by this abstract pathname that * satisfy the specified filter. The behavior of this method is the same * as that of the {@link #listFiles()} method, except that the pathnames in * the returned array must satisfy the filter. If the given {@code filter} * is {@code null} then all pathnames are accepted. Otherwise, a pathname * satisfies the filter if and only if the value {@code true} results when * the {@link FileFilter#accept FileFilter.accept(File)} method of the * filter is invoked on the pathname. * * @param filter * A file filter * * @return An array of abstract pathnames denoting the files and * directories in the directory denoted by this abstract pathname. * The array will be empty if the directory is empty. Returns * {@code null} if this abstract pathname does not denote a * directory, or if an I/O error occurs. * * @throws SecurityException * If a security manager exists and its {@link * SecurityManager#checkRead(String)} method denies read access to * the directory * * @since 1.2 * @see java.nio.file.Files#newDirectoryStream(Path,java.nio.file.DirectoryStream.Filter) */ public File[] listFiles(FileFilter filter) { String ss[] = list(); if (ss == null) return null; ArrayList files = new ArrayList(); for (String s : ss) { File f = new File(s, this); if ((filter == null) || filter.accept(f)) files.add(f); } return files.toArray(new File[files.size()]); } /** * Creates the directory named by this abstract pathname. * * @return true if and only if the directory was * created; false otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method does not permit the named directory to be created */ public boolean mkdir() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.createDirectory(this); } /** * Creates the directory named by this abstract pathname, including any * necessary but nonexistent parent directories. Note that if this * operation fails it may have succeeded in creating some of the necessary * parent directories. * * @return true if and only if the directory was created, * along with all necessary parent directories; false * otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkRead(java.lang.String)} * method does not permit verification of the existence of the * named directory and all necessary parent directories; or if * the {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method does not permit the named directory and all necessary * parent directories to be created */ public boolean mkdirs() { if (exists()) { return false; } if (mkdir()) { return true; } File canonFile = null; try { canonFile = getCanonicalFile(); } catch (IOException e) { return false; } File parent = canonFile.getParentFile(); return (parent != null && (parent.mkdirs() || parent.exists()) && canonFile.mkdir()); } /** * Renames the file denoted by this abstract pathname. * *

Many aspects of the behavior of this method are inherently * platform-dependent: The rename operation might not be able to move a * file from one filesystem to another, it might not be atomic, and it * might not succeed if a file with the destination abstract pathname * already exists. The return value should always be checked to make sure * that the rename operation was successful. * *

Note that the {@link java.nio.file.Files} class defines the {@link * java.nio.file.Files#move move} method to move or rename a file in a * platform independent manner. * * @param dest The new abstract pathname for the named file * * @return true if and only if the renaming succeeded; * false otherwise * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to either the old or new pathnames * * @throws NullPointerException * If parameter dest is null */ public boolean renameTo(File dest) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); security.checkWrite(dest.path); } if (dest == null) { throw new NullPointerException(); } if (this.isInvalid() || dest.isInvalid()) { return false; } return fs.rename(this, dest); } /** * Sets the last-modified time of the file or directory named by this * abstract pathname. * *

All platforms support file-modification times to the nearest second, * but some provide more precision. The argument will be truncated to fit * the supported precision. If the operation succeeds and no intervening * operations on the file take place, then the next invocation of the * {@link #lastModified} method will return the (possibly * truncated) time argument that was passed to this method. * * @param time The new last-modified time, measured in milliseconds since * the epoch (00:00:00 GMT, January 1, 1970) * * @return true if and only if the operation succeeded; * false otherwise * * @throws IllegalArgumentException If the argument is negative * * @throws SecurityException * If a security manager exists and its {@link * java.lang.SecurityManager#checkWrite(java.lang.String)} * method denies write access to the named file * * @since 1.2 */ public boolean setLastModified(long time) { if (time < 0) throw new IllegalArgumentException("Negative time"); SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setLastModifiedTime(this, time); } public boolean setReadOnly() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setReadOnly(this); } public boolean setWritable(boolean writable, boolean ownerOnly) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setPermission(this, FileSystem.ACCESS_WRITE, writable, ownerOnly); } public boolean setWritable(boolean writable) { return setWritable(writable, true); } public boolean setReadable(boolean readable, boolean ownerOnly) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setPermission(this, FileSystem.ACCESS_READ, readable, ownerOnly); } public boolean setReadable(boolean readable) { return setReadable(readable, true); } public boolean setExecutable(boolean executable, boolean ownerOnly) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); } if (isInvalid()) { return false; } return fs.setPermission(this, FileSystem.ACCESS_EXECUTE, executable, ownerOnly); } public boolean setExecutable(boolean executable) { return setExecutable(executable, true); } public boolean canExecute() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkExec(path); } if (isInvalid()) { return false; } return fs.checkAccess(this, FileSystem.ACCESS_EXECUTE); } public static File[] listRoots() { return fs.listRoots(); } public long getTotalSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_TOTAL); } public long getFreeSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_FREE); } public long getUsableSpace() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("getFileSystemAttributes")); sm.checkRead(path); } if (isInvalid()) { return 0L; } return fs.getSpace(this, FileSystem.SPACE_USABLE); } /* -- Temporary files -- */ private static class TempDirectory { private TempDirectory() { } // temporary directory location private static final File tmpdir = new File(AccessController .doPrivileged(new GetPropertyAction("java.io.tmpdir"))); static File location() { return tmpdir; } // file name generation private static final SecureRandom random = new SecureRandom(); static File generateFile(String prefix, String suffix, File dir) throws IOException { long n = random.nextLong(); if (n == Long.MIN_VALUE) { n = 0; // corner case } else { n = Math.abs(n); } // Use only the file name from the supplied prefix prefix = (new File(prefix)).getName(); String name = prefix + Long.toString(n) + suffix; File f = new File(dir, name); if (!name.equals(f.getName()) || f.isInvalid()) { if (System.getSecurityManager() != null) throw new IOException("Unable to create temporary file"); else throw new IOException("Unable to create temporary file, " + f); } return f; } } public static File createTempFile(String prefix, String suffix, File directory) throws IOException { if (prefix.length() < 3) throw new IllegalArgumentException("Prefix string too short"); if (suffix == null) suffix = ".tmp"; File tmpdir = (directory != null) ? directory : TempDirectory.location(); SecurityManager sm = System.getSecurityManager(); File f; do { f = TempDirectory.generateFile(prefix, suffix, tmpdir); if (sm != null) { try { sm.checkWrite(f.getPath()); } catch (SecurityException se) { // don't reveal temporary directory location if (directory == null) throw new SecurityException("Unable to create temporary file"); throw se; } } } while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0); if (!fs.createFileExclusively(f.getPath())) throw new IOException("Unable to create temporary file"); return f; } public static File createTempFile(String prefix, String suffix) throws IOException { return createTempFile(prefix, suffix, null); } public int compareTo(File pathname) { return fs.compare(this, pathname); } public boolean equals(Object obj) { if ((obj != null) && (obj instanceof File)) { return compareTo((File)obj) == 0; } return false; } public int hashCode() { return fs.hashCode(this); } public String toString() { return getPath(); } private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException { s.defaultWriteObject(); s.writeChar(separatorChar); // Add the separator character } private synchronized void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = s.readFields(); String pathField = (String)fields.get("path", null); char sep = s.readChar(); // read the previous separator char if (sep != separatorChar) pathField = pathField.replace(sep, separatorChar); String path = fs.normalize(pathField); UNSAFE.putObject(this, PATH_OFFSET, path); UNSAFE.putIntVolatile(this, PREFIX_LENGTH_OFFSET, fs.prefixLength(path)); } private static final long PATH_OFFSET; private static final long PREFIX_LENGTH_OFFSET; private static final sun.misc.Unsafe UNSAFE; static { try { sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe(); PATH_OFFSET = unsafe.objectFieldOffset( File.class.getDeclaredField("path")); PREFIX_LENGTH_OFFSET = unsafe.objectFieldOffset( File.class.getDeclaredField("prefixLength")); UNSAFE = unsafe; } catch (ReflectiveOperationException e) { throw new Error(e); } } /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 301077366599181567L; // -- Integration with java.nio.file -- private volatile transient Path filePath; public Path toPath() { Path result = filePath; if (result == null) { synchronized (this) { result = filePath; if (result == null) { result = FileSystems.getDefault().getPath(path); filePath = result; } } } return result; } }

 

关注
打赏
1665965058
查看更多评论
立即登录/注册

微信扫码登录

0.0449s