java.io.File类代表系统文件名(路径和文件名)
(1)File类常见的构造方法:
//以pathname为路径创建File对象,如果pathname是相对路径则默认当前路径在系统属性user.dir中存储 public 
File(String pathname) { if (pathname == null) { throw new 
NullPointerException(); } this.path = fs.normalize(pathname); this.prefixLength 
= fs.prefixLength(this.path); } //以parent为父路径,child为子路径创建File对象 public 
File(String parent, String child) 
(2)File类常用方法(方法名很直观)
1.通过File对象可以访问文件的属性
public boolean canRead() public boolean canWrite() public boolean exists() 
public boolean isFile() public boolean isDirectory() public boolean isHidden() 
//返回的是从1970年1月1日零时零分零秒到现在经历的毫秒数(为了效率高) public long lastModified() public long 
length() public String getName() public String getPath() 
2.通过File对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下)
public boolean createNewFile() public boolean delete() public boolean mkdir() 
//创建在路径中的一系列目录 public boolean mkdirs() 
(3)File方法的应用举例
package classinstance; import java.io.File; import java.io.IOException; /** * 
说明:文件类使用演示(在mydir1/mydir2目录下创建yuhua文件) * * @author huayu * @date 2018/8/30 4:29 
PM */ public class FileDemo { public static void main(String[] args) { String 
separator= File.separator; String filename="yuhua"; 
//separatory为了兼容性(因为在window中文件路径是"/""\"两种,而在linux中只能是"/") String 
directory="mydir1"+separator+"mydir2"; //还可以这么x写直接用"/",在windows跟linux都可以用 // 
String directory="mydir1/mydir2"; File file=new File(directory,filename); 
if(file.exists()){ System.out.println("文件名:"+file.getAbsolutePath()); 
System.out.println("文件大小:"+file.length()); }else { //在.class文件所在的最上层包的父路径下 
file.getParentFile().mkdirs(); try { file.createNewFile(); } catch (IOException 
e) { e.printStackTrace(); } } } } 
(4)应用小实验
package classinstance; import java.io.File; /** * 说明:递归列出文件目录及其所有子目录及文件树形展示出来 
* * @author huayu * @date 2018/8/30 5:11 PM */ public class PrintFileDirectory 
{ public static void main(String[] args) { File file=new 
File("/Users/huayu/Desktop/A"); System.out.println(file.getName()); 
tree(file,1); } public static void tree(File file,int level){ String preStr=""; 
for (int i = 0; i <level; i++) { //为了看的分层更清楚,建议多敲几个空格 preStr+=" "; } 
//列出当前目录的孩子们 File[] childs=file.listFiles(); for (int i = 0; i < childs.length; 
i++) { System.out.println(preStr+childs[i].getName()); 
if(childs[i].isDirectory()){ tree(childs[i],level+1); } } } } 结果 A d.txt C H B E
 
 
 
热门工具 换一换