码迷,mamicode.com
首页 > 其他好文 > 详细

File类方法

时间:2015-01-29 20:49:08      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

1.构造函数

里面用到下面三个变量

    //本地文件系统  
    static private FileSystem fs = FileSystem.getFileSystem();  
    //文件路径  
    private String path;  
    //路径长度  
    private transient int prefixLength;  

最基本的构造方法。

    public File(String pathname) {  
        if (pathname == null) {  
            throw new NullPointerException();  
        }  
            //将文件路径转为正常状态  
            this.path = fs.normalize(pathname);  
            //计算长度的路径字符串前缀,字符串必须是在正常的格式。  
        this.prefixLength = fs.prefixLength(this.path);  
    }  

另外有两个私有的构造函数+两个公有构造函数,里面只有对path和prefixLength复制的操作。

    //里面操作都一样,就是给两个变量赋值。  
    public File(File parent, String child)  
    public File(String parent, String child)  
      
    //前面的child为路径,后面的为文件  
    private File(String child, File parent)  
    //路径+路径长度  
    private File(String pathname, int prefixLength)  

以网络路径赋值的构造方法

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);
    }

*构造函数的路径

    new  File("src.txt");//出现在当前项目中的根目录。  
    new File("src/abc.txt");//在当前项目中的根目录下的src文件夹下。  
    new File("/abc.txt");//在当前盘符的根目录下。  
      
    new File(new File("C:\abc"),"xyz\abc.txt");  
    //创建的目录为C:\abc\xyz\abc.txt  

2.isDirectory和isFile

    //路径名表示的文件是否是一个目录  
    public boolean isDirectory() {  
        SecurityManager security = System.getSecurityManager();  
        if (security != null) {  
               //看这个路径是否有读权限  
            security.checkRead(path);  
        }  
            //里面没内容,这里为什么只用一个&符号?  
        return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY)  
            != 0);  
    }  
    //路径名表示的文件是否是一个标准文件。  
    public boolean isFile() {  
        SecurityManager security = System.getSecurityManager();  
        if (security != null) {  
            security.checkRead(path);  
        }  
        return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0);  
        }  

3.createNewFile创建文件

 1      /*SecurityManager 为安全管理器是一个允许应用程序实现安全策略的类。,权限分为以下类别:文件、套接字、网络、安全性、运行时、属性、AWT、反射和可序列化*/  
 2       
 3     public boolean createNewFile() throws IOException {  
 4         SecurityManager security = System.getSecurityManager();  
 5             //检查路径是否有写的权限。  
 6         if (security != null) security.checkWrite(path);  
 7            //创建文件,内部方法是native的  
 8         return fs.createFileExclusively(path);  
 9     }  
10       
11       
12     //下面是SecurityManager类中的方法。内部方法很复杂,看不懂。只知道是检查文件能不能写的功能。  
13     public void checkWrite(String file) {  
14         checkPermission(new FilePermission(file,   
15             SecurityConstants.FILE_WRITE_ACTION));  
16     }  

4.mkdir和mkdirs 创建目录

 1     //只创建一个目录,如果多级目录都不存在就失败  
 2     public boolean mkdir() {  
 3         SecurityManager security = System.getSecurityManager();  
 4         if (security != null) {  
 5             security.checkWrite(path);  
 6         }  
 7             //如果文件已经存在或者创建权限不够,返回false  
 8         return fs.createDirectory(this);  
 9     }  
10     //创建多级目录  
11     public boolean mkdirs() {  
12         if (exists()) {  
13             return false;  
14         }  
15         if (mkdir()) {  
16             return true;  
17         }  
18             File canonFile = null;  
19             try {  
20                 canonFile = getCanonicalFile();  
21             } catch (IOException e) {  
22                 return false;  
23             }  
24       
25         File parent = canonFile.getParentFile();  
26         return (parent != null && (parent.mkdirs() || parent.exists()) &&  
27             canonFile.mkdir());  
28     }  

5.list和listFiles

 1     public static void main(String args[]) throws IOException {  
 2         File f = new File("src");  
 3            //这里返回的是文件数组  
 4         File[] l = f.listFiles();  
 5         for (int i = 0; i < l.length; i++) {  
 6             System.out.println(l[i].getName());  
 7         }  
 8             //这里返回的是文件名字符串数组  
 9         String[] s = f.list();  
10         for (int i = 0; i < s.length; i++) {  
11             System.out.println(s[i]);  
12         }  
13     }  

这个是过滤器,实现FilenameFilter接口的accept方法。

一个例子,过滤文件名以.java结尾的文件  

 1 String[] names =f.list(new FilenameFilter() {  
 2             @Override  
 3             public boolean accept(File dir, String name) {  
 4                 if(name.endsWith(".java")){  
 5                     return true;  
 6                 }  
 7                 return false;  
 8             }  
 9 });  
10 //过滤文件名以.java结尾的文件 
    public String[] list(FilenameFilter filter) {  
        String names[] = list();  
        if ((names == null) || (filter == null)) {  
            return names;  
        }  
        ArrayList v = new ArrayList();  
        for (int i = 0 ; i < names.length ; i++) {  
                //这里的this为当前文件夹。为File类。  
            if (filter.accept(this, names[i])) {  
            v.add(names[i]);  
            }  
        }  
           //最后强转?  
        return (String[])(v.toArray(new String[v.size()]));  
    }  

 

File类方法

标签:

原文地址:http://www.cnblogs.com/hua2015/p/4260692.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!