Java--獲取指定目錄下指定suffix的文件

1. 獲取指定目錄下的文件

2. 獲取該目錄下與所給suffix相符的文件

package com.basic.io;

import java.io.File;
import java.util.Scanner;

public class GetFileFromTargetPath {
	
	private static Scanner scanner;
	private static int count;
	
	//Get Files from the target path
	public static void getFileName(String path){
		
		File file = new File(path);
		if (file.isDirectory()) {
			File[] dirFiles = file.listFiles();
			for (File f : dirFiles) {
				if (f.isDirectory()) { 
					//recursively call the getFileName method is path still a directory
					getFileName(f.getAbsolutePath());
				} else {
					//print the file name of the target path
					System.out.println(f.getAbsolutePath());
				}
			}
		} else {
			//print the file name of the target path
			System.out.println(file.getAbsolutePath());
		}
	}
	
	/**
	 * 
	 * @param filePath
	 * @param fileSuffix
	 */
	private static void getFileWithSuffix(String filePath, String fileSuffix) {
		// TODO Auto-generated method stub
		File file = new File(filePath);
		if (file.isDirectory()) {
			File[] dirFiles = file.listFiles();
			//int count = 0;
			for (File f : dirFiles) {
				if (f.isDirectory()) { 
					//recursively call the getFileWithSuffix method is path still a directory
					getFileWithSuffix(f.getAbsolutePath(), fileSuffix);
				} else {
					//print the file name of the target path
					//System.out.println(f.getAbsolutePath());
					if (f.getName().endsWith(fileSuffix)) {
						System.out.println(f.getAbsolutePath());
						count++;
					}
				}
			}
		} else {
			//print the file name of the target path
			if (file.getName().endsWith(fileSuffix)) {
				System.out.println(file.getAbsolutePath());
			} else {
				System.out.println("No file found in the path : " + filePath + " with suffix " + fileSuffix);
			}
			
		}
	}

	public static void main(String[] args) {
		scanner = new Scanner(System.in);
		
		//input the files path from console
	    System.out.print("Please input the files path :");
	    String filePath = scanner.next();
	    System.out.println();
	    System.out.print("Please input the files suffix : ");
	    String fileSuffix = scanner.next();
	    
	    //invoke the getFileName method
	    //getFileName(filePath);
	    
	    getFileWithSuffix(filePath, fileSuffix);
		if (count == 0)
			System.out.println("No file found in the path : " + filePath + " with suffix " + fileSuffix);
	
	}


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章