黑马程序员_File总结2

----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------

File类提供了一个使用有用的方法,listFiles()该方法返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。通过该方法可以方便的对指定目录中的文件进行遍历。当遍历到文件中的文件是目录时,则需要在次对文件中目录进行遍历。这时就在遍历的方法中再次调用了遍历方法,这种编程方法叫做递归。

下面是对一个指定目录的所有文件进行输出的代码实现。

import java.io.*;
class FileDemo3 
{
	public static void main(String[] args) 
	{
		File dir = new File("d:\\testdir");
		//showDir(dir,0);
		//System.out.println("n="+n);
		System.out.println(dir.delete());
	}
	public static String getLevel(int level)//该方法按照目录层级放回目录的前缀表示形式,实现了类似于windows系统中的文件显示效果。
	{
		StringBuilder sb = new StringBuilder();
		sb.append("|--");
		for(int x=0; x<level; x++)
		{
			//sb.append("|--");
			sb.insert(0,"|  ");

		}
		return sb.toString();
	}
	public static void showDir(File dir,int level)
	{
		
		System.out.println(getLevel(level)+dir.getName());
		level++;//在每次调用showDir()方法时,先记录文件所在的目录
		File[] files = dir.listFiles();
		for(int x=0; x<files.length; x++)
		{
			if(files[x].isDirectory())
				showDir(files[x],level);
			else
				System.out.println(getLevel(level)+files[x]);
		}
	}

}
除了文件遍历外,File类和Property类能较好的模拟软件的配置信息的实现。 Properties是hashtable的子类。 也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串。 是集合中和IO技术相结合的集合容器。 该对象的特点:可以用于键值对形式的配置文件。 那么在加载数据时,需要数据有固定格式:键=值。

import java.io.*;
import java.util.*;
class  RunCount
{
	public static void main(String[] args) throws IOException
	{
		Properties prop = new Properties();
		File file = new File("count.ini");
		if(!file.exists())
			file.createNewFile();		
		FileInputStream fis = new FileInputStream(file);
		prop.load(fis);		
		int count = 0;
		String value = prop.getProperty("time");		
		if(value!=null)
		{
			count = Integer.parseInt(value);
			if(count>=5)
			{
				System.out.println("您好,使用次数已到,拿钱!");
				return ;
			}

		}

		count++;
		prop.setProperty("time",count+"");
		FileOutputStream fos = new FileOutputStream(file);
		prop.store(fos,"");
		fos.close();
		fis.close();
		
	}
}


----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值