【发布时间】:2021-04-12 21:36:24
【问题描述】:
我需要从具有以下扩展名的文件夹(文件)中的每个文件中提取字符串部分,例如 png、jpg、jpeg、PNG、JPG、JPEG。文件命名约定如下(这是 2 个不同的文件,但它们唯一的共同点是获取 FILENAME 所需的 TIMESTAMP:
AIRLINECODE_PARTNERCODE_INVOICENO_timestamp.FILETYPE
FILENAME.FILETYPE_timestamp
示例文件名:
ET_PRH_4_20170309140404.png
gosalyn.png_20170309140404
从第一个读取字段后,我需要将每个大写字段写入数据库(例如 AIRLINECODE、PARTNERCODE 到 db 中的列)。我正在循环遍历“文件”中的“每个文件”。大写单词描述了将添加到数据库列中的字段。所以 AIRLINE_CODE 在数据库中有一个列,ET 将被放置在其中,以此类推。
以下是我到目前为止编写的代码,请您指导我如何将第二个文件的时间戳与第一个文件的时间戳进行比较,并将其存储在一个名为“timestamp”的字段中。您的帮助将不胜感激。谢谢
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
public class Pathnames {
public void readFilename() {
// try-catch block to handle exceptions
try {
File f = new File("C:\\Users\\rsaeed\\Desktop\\files");
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File f, String name) {
return name.endsWith(".png") || name.endsWith(".PNG") || name.endsWith(".jpg") || name.endsWith(".JPG") || name.endsWith(".jpeg") || name.endsWith(".JPEG");
}
};
// using a File class as an array
File[] files = f.listFiles(filter);
if(files != null) {
for(File eachFile : files) {
String[] partsOfName = eachFile.getName().split("_|\\."); // this part is correct and giving result in array as [ET, PRH, 4, 20170309140404, png]
//System.out.println(Arrays.toString(partsOfName));
// the following is wrong so what should be the code here that each file with .png_ is split and timestamp stored in secondFile array after which I can compare the two timestamps
if(eachFile.getName().contains(".png_")) {
String[] secondFile = eachFile.getName().split("\\_");
System.out.println(Arrays.toString(secondFile));
}
final String timestamp = partsOfName[3];
//System.out.println(timestamp);
}
}
// Get the names of the files by using the .getName() method
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public static void main(String args[]) {
Pathnames p = new Pathnames();
p.readFilename();
}
}
【问题讨论】: