我正在尝试按 unix 时间戳对目录中的文件进行排序。以下是目录中的文件名。
20151102-2148040042-1446522484838-Game21500052-x.realtime
20121102-2148010042-1446522484138-Game21500052-x.realtime
我需要在第二个 - 后对 unix 时间戳进行排序后获取文件。我怎样才能在java中做到这一点?
我可以像下面这样在 python 中做到这一点
def extract_timestamp(filename):
timestamp = filename.split('-')[2]
return timestamp
directory = '/home/ubuntu/assdd/'
# Get all files from the path
log_files = os.listdir(directory)
# Sort files by timestamp
log_files.sort(key=extract_timestamp)
# Get full path of each file
files = [os.path.join(directory,data_file) for data_file in log_files]
最佳答案
一种非常直接的方法:
List<String> fileNames = ... ;
List<String> sortedFileNames = fileNames.stream()
.sorted(Comparator.comparingLong(s -> Long.parseLong(s.split("-")[2])))
.collect(Collectors.toList());
sorted
调用需要一些解释:
它创建了一个Comparator
比较 Long
值( Comparator<Long>
)。它得到Long
通过将 fileName 字符串拆分为由 -
分隔的部分来获取值。然后,它获取结果分割的第三个元素,其中包含一个数字。然后它将这个数字转换为长整型。
关于java - 按文件名中第二秒后的时间戳字符串对目录中的文件进行排序 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42850826/