首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

对资料的一些操作

2012-11-08 
对文件的一些操作对文件的一些操作:File 类位于 java.io 包下。File 类的实例是不可变的;也就是说,一旦创建

对文件的一些操作

对文件的一些操作:File 类位于 java.io 包下。File 类的实例是不可变的;也就是说,一旦创建,File 对象表示的抽象路径名将永不改变。 结合实例对File 进行解析:

?

?

/*

?* 查询指定文件夹下,包含的目录文件和标准文件的个数,

?* 并计算文件夹的大小

?*/

?

?

? //统计指定文件夹下标准文件的个数

? ? ? ?public int countFile1(String path){

? ? int count1=0;

? ?

? ? ? //根据路径创建一个文件对象

? ?java.io.File file = new java.io.File(path);

? ?

? ? ? ? ?//判断文件是否存在

if(!file.exists()){

System.out.println("给定的文件路径不存在!!");

return 0;

}

?//如果存在的话,就将这个文件夹下面的所有文件对象装入数组中

java.io.File[] fs = file.listFiles();

if(fs==null){

System.out.println("给定的文件路径不是文件夹。");

return 0;

}

//遍历文件数组

for(int i=0;i<fs.length;i++){

//得到一个文件

java.io.File f = fs[i];

//得到文件路径

String str = f.getAbsolutePath();

//如果找到的是一个标准文件

if(f.isFile()){

count1++;

//System.out.println("找到一个文件:"+str);

//如果找到的是一个文件夹

}else if(f.isDirectory()){

//递归调用

count1+=countFile1(str);

}

}

return count1;

}

?

?

?

?

文件系统对于文件的一些操作,就是对文件对象的操作。

?

创建文件对象的方式有四种:

1,File(File?parent, String?child) ??根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。

2,File(String pathname)?通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。

3,File(String?parent, String?child)根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。

4,File(URI?uri)?通过将给定的 file: URI 转换为一个抽象路径名来创建一个新的 File 实例。

?

本文使用了最常用的方式,根据文件的路径来创建文件对象。

?

?

?

?//计算指定目录文件的大小

? ? ? ?public long countSpace(String path){

? ? ? long space=0;

? ? ? //创建文件对象

? ? ? java.io.File file=new java.io.File(path);

? ? ? //将文件夹下所有的文件装入

? ? ? java.io.File[] fs=file.listFiles();

? ? ??

? ? ? //遍历文件数组

? ? ? ? ? for(int i=0;i<fs.length;i++){

? ? ? ? //得到一个文件

? ? ? ? ?java.io.File f=fs[i];

? ? ? ? ?//得到文件的绝对地址

? ? ? ? ?String str=f.getAbsolutePath();

? ? ? ? //如果找到的是一个标准文件

? if(f.isFile()){

? space=space+f.length();

?

? //如果找到的是一个文件夹

? }else if(f.isDirectory()){

?

? //递归调用

? space=space+countSpace(str);

? }

? }

? ? ? ? ??

? ? ??

? ? ? return space;

?

? ? ? ?}

?

?

?

热点排行