[英]Java: How to extract the largest name from multiple folders kept at a path into a variable where folder names are all numeric?
There is a directory which has many folders.有一个目录,里面有很多文件夹。 The folder names are all numeric.
文件夹名称都是数字。 How to extract the folder name which has the greatest value into an integer variable in java?
如何将具有最大值的文件夹名称提取到 java 中的 integer 变量中?
For example: Lets say directory .../home/user
has following folders:例如:假设目录
.../home/user
有以下文件夹:
.../home/user/19620918
.../home/user/19620919
.../home/user/19620920
How to get x = 19620920
, where x
is lets say the integer variable, using the simplest and most efficient code?如何使用最简单和最有效的代码获得
x = 19620920
,其中x
可以说是 integer 变量?
Using a Files.list()
, you can use the following approach:使用
Files.list()
,您可以使用以下方法:
public static OptionalInt getMaxNumericFilename(Path path) {
try (Stream<Path> files = Files.list(path)) {
return files
.filter(Files::isDirectory)
.map(Path::getFileName)
.map(Path::toString)
.mapToInt(Integer::parseInt)
.max();
} catch (IOException e) {
return OptionalInt.empty();
}
}
Example usage:示例用法:
Path path = Path.of(".../home/user");
OptionalInt max = getMaxNumericFilename(path);
System.out.println(max.getAsInt());
If the OptionalInt
is empty, there are no present directories.如果
OptionalInt
为空,则不存在当前目录。 If you want to add additional resiliency, you can filter if the filename is an int
before parsing with Integer::parseInt
which can throw an exception.如果您想增加额外的弹性,您可以在使用
Integer::parseInt
解析之前过滤文件名是否为int
,这可能会引发异常。
This solution will work for filename numbers up to Integer.MAX_VALUE
(2.147.483.647).此解决方案适用于最大为
Integer.MAX_VALUE
(2.147.483.647) 的文件名编号。 Consider using long
or BigDecimal
if required.如果需要,请考虑使用
long
或BigDecimal
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.