一、File类的使用
由于file类是一个基础类,所以我们从file类开始了解。(SE有完善的中文文档,建议阅读)
构造器:
常用方法:——完整方法请参见API API API!!!
File做的是面上的事——文件的新建、删除、重命名等。有关文件内容的操作,需要流来进行,所以,它经常作为形参。
文件名:
测试文件:
测试代码:
@Testpublic voidtest1() {//通过绝对路径创建File对象——对应一个文件或者文件夹
File file = new File("D:\\test\\hello.txt");//getName()——文件或目录名
System.out.println("#getName:"+file.getName());//getPath()——路径字符串,若是相对路径,返回相对路径字符串
System.out.println("#getPath:"+file.getPath());//getAbsoluteFile()——绝对路径形式,返回File
System.out.println("#getAbsoluteFile() "+file.getAbsoluteFile());//getAbsolutePath()——绝对路径字符串
System.out.println("#getAbsolutePath() "+file.getAbsolutePath());//getParent() ——返回父目录
System.out.println("#getParent() "+file.getParent());
}
View Code
测试结果:
文件检测:
测试文件:
测试代码:
@Testpublic voidtest2() {
File file1= new File("D:\\test\\hello.txt"); //文件
File file2 = new File("D:\\test\\childDir"); //文件夹//exists()——文件或目录是否存在
System.out.println("#exists()"+file1.exists());//canRead() canWrite() ——是否可读可写
System.out.println("#canRead()"+file1.canRead());
System.out.println("#canWrite()"+file1.canWrite());//isFile() isDirectory() ——是否是文件/目录
System.out.println("#isFile()"+file1.isFile());
System.out.println("#isFile()"+file2.isFile());
System.out.println("#isDirectory()"+file1.isDirectory());
System.out.println("#isDirectory()"+file2.isDirectory());
}
View Code
测试结果:
获取常规文件信息:
测试文件:上文hello.txt
测试代码&