,转载请注明出处:http://blog.youkuaiyun.com/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;
- }
- }
本文介绍了一个简单的Java程序,该程序能够从指定目录中筛选出符合特定前缀和后缀条件的文件,并从中找到最大编号的文件名。程序首先检查路径是否以斜杠结尾,然后遍历目录下的所有文件,对比文件名的前缀和后缀,去除前后缀后的部分转换为整数进行大小比较,最终返回最大编号的文件名。
855

被折叠的 条评论
为什么被折叠?



