`

遍历目录中的文件,得到文件名称

    博客分类:
  • J2SE
阅读更多
package com.jinbu.sourceFile;
import java.io.File;
import java.util.ArrayList;

public class TxtSourceFile{

	 private String SUFFIX = ".txt";// 文件后缀名称
	 private ArrayList<String> filelist; 
	 private int fileIndex = 0;
	 private boolean hasDir;//是否允许遍历子目录
	 public TxtSourceFile(String filePath,boolean hasDir){
		this.hasDir = hasDir;
		filelist = new ArrayList<String>();
		this.refreshFileList(filePath);
	 }
	 
	 /**
	  * 得到文件列表
	  * @param filePath
	  */
	 private void refreshFileList(String filePath) { 
		 File dir = new File(filePath);
		 
	     File[] files = dir.listFiles(); 
	     
	     if (files == null && dir != null){
	    	//不是目录
	    	 filelist.add(dir.getAbsolutePath());
	     }else{
	    	 //是目录
		     for (int i = 0; i < files.length; i++) { 
		    	 //判断是否是子目录
		    	 if (files[i].isDirectory() && hasDir) { 
		    		 refreshFileList(files[i].getAbsolutePath()); 
		         } else { 
		        	 String strFileName = files[i].getAbsolutePath().toLowerCase();
		        	 if(strFileName.endsWith(SUFFIX)){
		        		 filelist.add(strFileName);
		        	 }
		         } 
		     }
	     }
	     
	 }
	 
	 /**
	  * 是否有下一个文件
	  * @return File
	  */
	 public boolean hasNext(){
		 if(fileIndex >= filelist.size() || filelist.get(fileIndex) == null){
			 return false;
		 }else{
			 return true;
		 }
	 }
	 
	 /**
	  * 得到下一个文件
	  * @return File
	  */
	 public File next(){
		 File file = new File((String) filelist.get(fileIndex));
		 fileIndex = fileIndex + 1;	 
		 return file;
	 }
	 
	 /**
	  * 文件数量
	  * @return
	  */
	 public int fileCount(){
		int fileCount = 0;
		fileCount = filelist.size(); 
		return fileCount;
	 }
	
	 /**
	  * 测试
	  * @param args
	  */
	 public static void main(String[] args) {
	        
		 TxtSourceFile f = new TxtSourceFile("c:\\test",true);
		 for (int i = 0; i <f.filelist.size(); i++) {
			System.out.println(f.filelist.get(i));
		}
	}
	
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics