读取某个文件夹下指定前缀和后缀的文件,并且返回指定文件的功能性Demo

,转载请注明出处:http://blog.****.net/qq_25827845/article/details/59488796

 

实现功能:

  • 读取指定路径的文件夹,读取其中的文件
  • 选择有指定后缀和前缀的文件
  • 比较去除后缀和前缀之后剩余部分的大小
  • 返回指定文件

比如说有这样一个文件夹:

读取某个文件夹下指定前缀和后缀的文件,并且返回指定文件的功能性Demo

执行代码后结果如下:

读取某个文件夹下指定前缀和后缀的文件,并且返回指定文件的功能性Demo

 

 

代码如下:

[java] view plain copy
  1. package com.ywq;  
  2.   
  3. import java.io.*;  
  4. import java.util.ArrayList;  
  5. import java.util.Collections;  
  6. import java.util.List;  
  7.   
  8. public class Client {  
  9.   
  10.      public static void main(String[] args) {  
  11.         try {  
  12.             String targetFile = getFile("D:/ywq","文本",".txt");  
  13.             System.out.println(targetFile);  
  14.         } catch (IOException e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18.      public static String getFile(String filepath, String prefix, String suffix) throws FileNotFoundException, IOException {  
  19.          filepath = checkFilePathEnd(filepath);  
  20.          File file = new File(filepath);  
  21.          Integer maxNum = null;  
  22.          if (!file.isDirectory()) {  
  23.                  return null;  
  24.          }   
  25.          List<Integer> numList = new ArrayList<Integer>();  
  26.          String[] filelist = file.list();  
  27.          for (int i = 0; i < filelist.length; i++) {  
  28.              File readfile = new File(filepath + filelist[i]);  
  29.              Integer num = getNum(readfile, prefix, suffix);  
  30.              if (num!=null) {  
  31.                 numList.add(num);  
  32.               }  
  33.           }  
  34.           Collections.sort(numList);  
  35.           if (!numList.isEmpty()) {  
  36.               maxNum = numList.get(numList.size()-1);  
  37.           }else{  
  38.               return  null;  
  39.           }  
  40.          return prefix+maxNum+suffix;  
  41.      }  
  42.        
  43.      public static String  checkFilePathEnd(String filepath){  
  44.          if(!filepath.endsWith("/"))  
  45.              filepath =filepath + "/";  
  46.         return filepath;  
  47.            
  48.      }  
  49.        
  50.      public static Integer getNum(File readfile, String prefix, String suffix ){  
  51.          Integer number = null;  
  52.          if (!readfile.isDirectory() && readfile.getName().endsWith(suffix)  
  53.                  && readfile.getName().startsWith(prefix)) {  
  54.                  String num = readfile.getName().substring(prefix.length(),  
  55.                          readfile.getName().length()-suffix.length());  
  56.                  try {  
  57.                      number = Integer.parseInt(num);  
  58.                 } catch (Exception e) {  
  59.                     return number;  
  60.                 }  
  61.                    
  62.                    
  63.          }   
  64.         return number;  
  65.      }  
  66. }