比较和thencomparingint在同一字符串中不起作用
我正在尝试获取一些.txt文件,按顺序读取它们,然后将其内容(带有逻辑)写入Excel表。 这些文件是这样的:
FileB_60.txt
FileB_90.txt
FileB_120.txt
fileA_60.txt
fileA_90.txt
fileA_120.txt
最后,我希望像这样读取它们,按名称和数字订购。如果我不使用任何分类步骤,则它们随机阅读。
String fileExtension = ".txt";
try (Stream<Path> paths = Files.walk(Paths.get(resourcesPath))) {
Comparator<Path> byName = Comparator.comparing(p -> p.getFileName().toString());
Comparator<Path> byNameAndNumber = byName.thenComparingInt(p -> Integer.parseInt(p.getFileName().toString().split("_")[1].replace(fileExtension, "")));
for (Path eachFilePath : paths
.filter(p -> p.getFileName().toString().endsWith(fileExtension))
.sorted(byNameAndNumber)
.collect(Collectors.toList()))
...
这样,他们就会读:
FileB_120.txt
FileB_60.txt
FileB_90.txt
fileA_120.txt
fileA_60.txt
fileA_90.txt
因此,似乎只用名字订购(首先是大写字母) 我想知道我在这里是否做错了,因为我在同一字符串中进行排序
I'm trying to get some .txt files , reading them in order and then writing their content( with some logic) into an excel sheet.
The files are named like this:
FileB_60.txt
FileB_90.txt
FileB_120.txt
fileA_60.txt
fileA_90.txt
fileA_120.txt
In the end, I want them to be read just like that, ordered by name and number. If I don't use any sorting step, they're read randomly.
String fileExtension = ".txt";
try (Stream<Path> paths = Files.walk(Paths.get(resourcesPath))) {
Comparator<Path> byName = Comparator.comparing(p -> p.getFileName().toString());
Comparator<Path> byNameAndNumber = byName.thenComparingInt(p -> Integer.parseInt(p.getFileName().toString().split("_")[1].replace(fileExtension, "")));
for (Path eachFilePath : paths
.filter(p -> p.getFileName().toString().endsWith(fileExtension))
.sorted(byNameAndNumber)
.collect(Collectors.toList()))
...
This way, they're read like:
FileB_120.txt
FileB_60.txt
FileB_90.txt
fileA_120.txt
fileA_60.txt
fileA_90.txt
So it seems like it's ordering only by the name (capital letter first)
I was wondering if I'm doing something wrong here, since I'm sorting within the same string
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关于
tencomparing ...
方法:仅在初始比较器(在示例中称为byname
)时才使用比较器注入。认为这两个元素是相等的,在您的示例中绝对不会。比较器
byname
必须仅比较文件名的第一部分(_
)。One important thing about
thenComparing...
methods: the comparator injected is only used when the initial comparator (calledbyName
in your example) considers the 2 elements are equal, which is never the case in your example.The comparator
byName
must compare only the first part of the file name (the one before the_
).