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);
}
}