----------- 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學習型技術博客、期待與您交流! ------------