gpt4 book ai didi

java - java中如何从文件名中选取特定位置

转载 作者:行者123 更新时间:2023-12-01 11:59:40 25 4
gpt4 key购买 nike

我有以下类(class),文件夹中的文件类似于(xyz_1_071_basefiles_03272_30087.txt。)

并且我粗体的位置我只想选择该部分并对其进行排序,如果该值不是像下面的示例那样添加

这样就好了

10000
10001
10002
10003
10004

但是如果像下面这样

10000
10001
10003
10004

然后我想显示这两个文件数字 10001、10003,因为这两个数字之间缺少 10002,下面是我到目前为止所做的代码。

public loopMe() {

File dir = new File(path);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
//System.out.println(child.getName());
String filename = child.getName();
String filename1 = filename.substring(24,30);
System.out.println(filename1);
}
} else {

}

}

最佳答案

更新以包含从文件名获取数字的方法:

Integer sequenceNo = Integer.parseInt(filename.split("_")[4]);

这将在 _ 字符上分割文件名,然后检索第四个元素。

在现有代码的基础上,将提取的文件名部分转换为整数(如上所示),将它们全部放入列表中并对其进行排序,有点像这样:

List<Integer> filenames = new ArrayList<>();
for (File child : directoryListing) {
String filename = child.getName();
String filename1 = filename.substring(24,30);
filenames.add(Integer.parseInt(filename1));
}
Collections.sort(filenames);

现在循环列表,查看当前条目是否存在 - 1 > 1 差异,如下所示(未经测试):

int previousInSequence = filenames.get(0);
for (Integer currentSequence : filenames) {
if (currentSequence - previousInSequence > 1) {
// you have missing files
// currentSequence - previousInSequence will tell you how many

}
}

关于java - java中如何从文件名中选取特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28068864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com