Note that when the above file was in the directory, I sometimes wanted to extract only a unique character string from the file name. I checked the sauce but didn't use it, so it's a memorial service
Java SE 8 (jdk1.8.0_121)
GetFileName.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class GetFileName {
public static void main(String[] args) {
String fileLeadName = "hogehoge_"; //First character
String fileEndName = "_hoge"; //Last character
File file = new File("File directory path name");
File files[] = file.listFiles();
List<File> fileList = new ArrayList<File>();
for(File fileAndDir : files) {
//List only file names
if(fileAndDir.isFile()){
fileList.add(fileAndDir);
}
}
for(File originalFileName : fileList) {
// getName()Stringed with
String fileName = originalFileName.getName();
//Determine if the first and last characters are included
if(fileName.indexOf(leadFileName) != -1 && fileName.indexOf(endFileName) != -1) {
// fileLeadName.indexOf(fileLeadName)Is 0, so omitted
String fileUniqueName = fileName.substring(fileLeadName.length()
,fileName.lastIndexOf(fileEndName));
System.out.println(fileUniqueName);
}
}
}
}
result
huga
sample
test
If the character string at the end is not a fixed character string such as a date, consider it separately.
If it is separated by "\ _" as above, use lastIndexOf (fileEndName)
Is it possible to deal with it by setting it to lastIndexOf ('_')
?
Recommended Posts