File源码理解

1.构造函数

最基本的构造方法。

Java代码 复制代码 收藏代码
  1. public File(String pathname) {
  2. if (pathname == null) {
  3. throw new NullPointerException();
  4. }
  5. //将文件路径转为正常状态
  6. this.path = fs.normalize(pathname);
  7. //计算长度的路径字符串前缀,字符串必须是在正常的格式。
  8. this.prefixLength = fs.prefixLength(this.path);
  9. }
public File(String pathname) {
	if (pathname == null) {
	    throw new NullPointerException();
	}
        //将文件路径转为正常状态
        this.path = fs.normalize(pathname);
        //计算长度的路径字符串前缀,字符串必须是在正常的格式。
	this.prefixLength = fs.prefixLength(this.path);
}

里面用到下面三个变量

Java代码 复制代码 收藏代码
  1. //本地文件系统
  2. static private FileSystem fs = FileSystem.getFileSystem();
  3. //文件路径
  4. private String path;
  5. //路径长度
  6. private transient int prefixLength;
//本地文件系统
static private FileSystem fs = FileSystem.getFileSystem();
//文件路径
private String path;
//路径长度
private transient int prefixLength;

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

Java代码 复制代码 收藏代码
  1. //里面操作都一样,就是给两个变量赋值。
  2. public File(File parent, String child)
  3. public File(String parent, String child)
  4. //前面的child为路径,后面的为文件
  5. private File(String child, File parent)
  6. //路径+路径长度
  7. private File(String pathname, int 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)

以网络路径赋值的构造方法,目前我还不会用这个。似乎是file://192.168.1.201/wan/a.txt 这样的链接。

Java代码 复制代码 收藏代码
  1. public File(URI uri) ;
 public File(URI uri) ;

2.createNewFile创建文件

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

public boolean createNewFile() throws IOException {
	SecurityManager security = System.getSecurityManager();
        //检查路径是否有写的权限。
	if (security != null) security.checkWrite(path);
       //创建文件,内部方法是native的
	return fs.createFileExclusively(path);
}


//下面是SecurityManager类中的方法。内部方法很复杂,看不懂。只知道是检查文件能不能写的功能。
public void checkWrite(String file) {
	checkPermission(new FilePermission(file, 
	    SecurityConstants.FILE_WRITE_ACTION));
}

3.isDirectory和isFile

如果文件或者文件夹不存在的话这两个方法都返回false

Java代码 复制代码 收藏代码
  1. //路径名表示的文件是否是一个目录
  2. public boolean isDirectory() {
  3. SecurityManager security = System.getSecurityManager();
  4. if (security != null) {
  5. //看这个路径是否有读权限
  6. security.checkRead(path);
  7. }
  8. //里面没内容,这里为什么只用一个&符号?
  9. return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY)
  10. != 0);
  11. }
  12. //路径名表示的文件是否是一个标准文件。
  13. public boolean isFile() {
  14. SecurityManager security = System.getSecurityManager();
  15. if (security != null) {
  16. security.checkRead(path);
  17. }
  18. return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0);
  19. }
//路径名表示的文件是否是一个目录
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);
    }

4.mkdir和mkdirs 创建目录

Java代码 复制代码 收藏代码
  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. File parent = canonFile.getParentFile();
  25. return (parent != null && (parent.mkdirs() || parent.exists()) &&
  26. canonFile.mkdir());
  27. }
//只创建一个目录,如果多级目录都不存在就失败
public boolean mkdir() {
	SecurityManager security = System.getSecurityManager();
	if (security != null) {
	    security.checkWrite(path);
	}
        //如果文件已经存在或者创建权限不够,返回false
	return fs.createDirectory(this);
}
//创建多级目录
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());
}

看到这里已经觉得没意思了,里面的内容都看不了,都是抽象和native。

5.list和listFiles

这两个方法都是先判断有没有读权限,然后一个native方法结束。下面是使用

Java代码 复制代码 收藏代码
  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. }
public static void main(String args[]) throws IOException {
	File f = new File("src");
       //这里返回的是文件数组
	File[] l = f.listFiles();
	for (int i = 0; i < l.length; i++) {
		System.out.println(l[i].getName());
	}
        //这里返回的是文件名字符串数组
	String[] s = f.list();
	for (int i = 0; i < s.length; i++) {
		System.out.println(s[i]);
	}
}

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

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

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结尾的文件
String[] names =f.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if(name.endsWith(".java")){
					return true;
				}
				return false;
			}
});
//过滤文件名以.java结尾的文件

Java代码 复制代码 收藏代码
  1. public String[] list(FilenameFilter filter) {
  2. String names[] = list();
  3. if ((names == null) || (filter == null)) {
  4. return names;
  5. }
  6. ArrayList v = new ArrayList();
  7. for (int i = 0 ; i < names.length ; i++) {
  8. //这里的this为当前文件夹。为File类。
  9. if (filter.accept(this, names[i])) {
  10. v.add(names[i]);
  11. }
  12. }
  13. //最后强转?
  14. return (String[])(v.toArray(new String[v.size()]));
  15. }
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()]));
}

6.delete

只能删除空文件夹和单个文件。

7.构造函数的路径

Java代码 复制代码 收藏代码
  1. new File("src.txt");//出现在当前项目中的根目录。
  2. new File("src/abc.txt");//在当前项目中的根目录下的src文件夹下。
  3. new File("/abc.txt");//在当前盘符的根目录下。
  4. new File(new File("C:\abc"),"xyz\abc.txt");
  5. //创建的目录为C:\abc\xyz\abc.txt
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值