关于一些file类的基础代码

在java中,file可以获取文件的信息和属性

用file创建目录,并列出里面的内容

 File f=new File("d:\\"); 
		f.mkdir();             //创建目录
		 File[] files=f.listFiles();
		 for(File file1:files){
			 System.out.println(file1);
在f盘中创建两个文件夹lenovo 和study,在lenovo文件里面创建一个文档hello.txt,在study文件夹里面创建一个文档log.txt
File f3=new File("f://lenovo");
		f3.mkdirs();
		File f4=new File("f://lenovo//hello.txt");	
		try {
			f4.createNewFile();
			
				File[] f=f3.listFiles();
				for(File s:f){
					if(s.isDirectory()){
						System.out.println("目录:"+s.getName()+" "+"长度:"+s.length()+"\t上一级文件:"+s.getPath());
}
					else{
						System.out.println("文件:"+s.getName()+" "+"长度:"+s.length()+"\t上一级文件:"+s.getPath());
					}}	
			}
		 catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		File f5=new File("f://lenovo//study//log.txt");
		try {
			f5.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
判断文件是否为文件夹,如果是就列出来,并列出长度,如果不是就为文档,并列出文档的长度

File[] files=file.listFiles();
		for (File f : files) {
			if(f.isDirectory()){
				System.out.println("目录:"+f.getName()+" "+"长度:"+f.length());
				//递归调用
				showAllFile(f);
			}else{
				System.out.println("文件:"+f.getName()+" "+"长度:"+f.length());
			}	
	}


猜你喜欢

转载自blog.csdn.net/l_y_j_21/article/details/72615034