Java--获取指定目录下指定suffix的文件

本文介绍了如何使用Java编程获取指定目录下的所有文件,并进一步筛选出具有特定suffix的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值