,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/59488796)
实现功能:
- 读取指定路径的文件夹,读取其中的文件
- 选择有指定后缀和前缀的文件
- 比较去除后缀和前缀之后剩余部分的大小
- 返回指定文件
比如说有这样一个文件夹:
执行代码后结果如下:
代码如下:
- package com.ywq;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- public class Client {
- public static void main(String[] args) {
- try {
- String targetFile = getFile("D:/ywq","文本",".txt");
- System.out.println(targetFile);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static String getFile(String filepath, String prefix, String suffix) throws FileNotFoundException, IOException {
- filepath = checkFilePathEnd(filepath);
- File file = new File(filepath);
- Integer maxNum = null;
- if (!file.isDirectory()) {
- return null;
- }
- List<Integer> numList = new ArrayList<Integer>();
- String[] filelist = file.list();
- for (int i = 0; i < filelist.length; i++) {
- File readfile = new File(filepath + filelist[i]);
- Integer num = getNum(readfile, prefix, suffix);
- if (num!=null) {
- numList.add(num);
- }
- }
- Collections.sort(numList);
- if (!numList.isEmpty()) {
- maxNum = numList.get(numList.size()-1);
- }else{
- return null;
- }
- return prefix+maxNum+suffix;
- }
- public static String checkFilePathEnd(String filepath){
- if(!filepath.endsWith("/"))
- filepath =filepath + "/";
- return filepath;
- }
- public static Integer getNum(File readfile, String prefix, String suffix ){
- Integer number = null;
- if (!readfile.isDirectory() && readfile.getName().endsWith(suffix)
- && readfile.getName().startsWith(prefix)) {
- String num = readfile.getName().substring(prefix.length(),
- readfile.getName().length()-suffix.length());
- try {
- number = Integer.parseInt(num);
- } catch (Exception e) {
- return number;
- }
- }
- return number;
- }
- }