JAvaローカルフォルダ内のファイルを読み込み、並べ替え

3288 ワード

まずクラスを定義します.ファイルのソートに使用

class SortFile {
	public  long size;  
	public  long date;  
	public  String name;  
	public SortFile(String name, long date, long size) {    
		this.name = name;    
		this.date = date;     
		this.size = size;  
	}

	public static SortFile[] sort(SortFile[] src, String mark, boolean rule) {   
		if (rule) {//  
			
			for (int i = src.length; i > 1; i--) {   
				for (int j = 0; j < i - 1; j++) {     
					boolean change = false;        
					if (mark.equals("name")) {        
						if (src[j].name.compareTo(src[j + 1].name) > 0)  {  
							change = true;         
						} 
					}
					else if (mark.equals("date")) {  
							
							if (src[j].date  > src[j + 1].date) {       
								change = true;         
							} 
					}
					else {           
							if (src[j].size > src[j + 1].size)  {   
							change = true;            
							}
					}              
					if (change) {           
							SortFile temp = src[j];  
							src[j] = src[j + 1];      
							src[j + 1] = temp;       
					}              
				}         
			} 
		}		
				
		else {    //   
			for (int i = src.length; i > 1; i--) {   
				for (int j = 0; j < i - 1; j++) {     
					boolean change = false;        
					if (mark.equals("name")) {        
						if (src[j].name.compareTo(src[j + 1].name) < 0)  {  
							change = true;         
						} 
					}
					else if (mark.equals("date")) {  
							
						if (src[j].date  < src[j + 1].date) {       
								change = true;         
							} 
					}
					else {           
							if (src[j].size < src[j + 1].size)  {   
							change = true;            
							}
					}              
					if (change) {           
							SortFile temp = src[j];  
							src[j] = src[j + 1];      
							src[j + 1] = temp;       
					}              
				}         
			}      
		}      
		return src;    
								
	}
		

// 
ArrayList al = new ArrayList();
		File f = new File("E:\\test");
		String[] names = f.list();
		for (int i = 0; i < names.length; i++) { 
			File fs = new File(f, names[i]);
						
						SortFile sf = new SortFile(names[i],fs.lastModified(), fs.length()); 
			al.add(sf);		}
// 
SortFile[] sfSrc = new SortFile[al.size()];
		
		
		for(int i=0;i<al.size();i++){
			sfSrc[i] = (SortFile) al.get(i);
			
			System.out.println(sfSrc[i].name+"   "+sfSrc[i].size+"     "+sfSrc[i].date);
		}
//  date ,name ,size  

SortFile[] forName = SortFile.sort(sfSrc,"date",true);
//true  ,false 

		for(int i=0;i<forName.length;i++){
			System.out.println(forName[i].name+"    "+forName[i].size+"    "+forName[i].date);
		}