获取指定文件夹下文件的名称,并根据需求截取子串
需求:我要获取下面文件夹下的所有文件的名称,并得到子串:
源码:
package cn.mike.demo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author MikeSun
* @usage 这个程序用来获取指定文件夹下文件的名称;
*/
public class GetFileNames {
private static String extension;// 扩展名
private static List<File> srcFiles;// 存放所有符合条件的文件
static {
extension = ".swf";// 获取".swf"文件
srcFiles = new ArrayList<File>();
}
public static void main(String[] args) {
File srcFolder = new File("E:\\BaiduYun\\BEC资料大全(中级)\\沪江英语BEC\\职场俚语");
iterateGetFiles(srcFolder);
String fileName = null;
int number = 0;// 编号
int dashIndex = -1;// "-"符号的位置
for (File each : GetFileNames.srcFiles) {
fileName = each.getName();
dashIndex = fileName.indexOf("-");
fileName = fileName.substring(dashIndex + 2, fileName.length() - 4);
System.out.println(String.format("%02d", ++number) + "_" + fileName);
}
}
private static void iterateGetFiles(File srcFile) {
// 如果是文件夹,就继续深入遍历
if (srcFile.isDirectory()) {
File[] files = srcFile.listFiles();
for (File each : files) {
iterateGetFiles(each);
}
} else if (srcFile.getAbsolutePath().endsWith(GetFileNames.extension)) {
// 不是文件夹而且文件格式为swf,就将该文件添加到待命名文件的list集合中
GetFileNames.srcFiles.add(srcFile);
}
}// end method-iterateGetFiles
}// end class-GetFileNames
最终输出:
01_Debbie Talks Shop
02_Our Cutting Edge Hi-Tech Line
03_Roger Gets the Inside Track
04_That Spot Has a Catchy Jingle
05_Earl Got Called on the Carpet
06_Mr. Smith, You Have the Floor
07_Kyle's Making Big Bucks
08_A lot of Wheeling and Dealing
09_Bill Reinvents the Wheel
10_Tanya Travels Light
11_Chuck Wears Several Hats
12_Send This to the VP's CPA ASAP, OK$%
13_Lisa Gets a Fair Shake
14_My Hard Drive Got a Virus and Crashed
15_Nancy Finally Got a Cush Job
16_Joe Got an ISP for Surfing the Net