java路径 标准化,Java:如何使用nio Path标准化路径?

这篇博客探讨了如何使用 Java NIO 中的 Path 类来规范化路径,类似于 java.io.File 的行为。作者提供了代码示例,展示了如何将不同形式的路径转换为统一格式,但注意这种方法并不跨平台,例如在 Windows 系统上可能不适用。为了实现跨平台的解决方案,建议使用内存文件系统并打开 Unix 文件系统进行路径操作。
摘要由CSDN通过智能技术生成

One of the really nice things about java.io.File is that it can normalize paths to a predictable format.

new File("/", inputPath).getPath() always returns a string with relative paths normalized out, and always starting and ending with predictable path separators.

Is there a way to do this with the new nio Path or Paths classes?

(Note also that I am dealing with abstract paths for other systems, this has nothing to do with any local filesystem)

Further examples of behavior I want:

- "/foo" -> "/foo"

- "//foo/" -> "/foo"

- "foo/" -> "/foo"

- "foo/bar" -> "/foo/bar"

- "foo/bar/../baz" -> "/foo/baz"

- "foo//bar" -> "/foo/bar"

解决方案

This code works:

public final class Foo

{

private static final List INPUTS = Arrays.asList(

"/foo", "//foo", "foo/", "foo/bar", "foo/bar/../baz", "foo//bar"

);

public static void main(final String... args)

{

Path path;

for (final String input: INPUTS) {

path = Paths.get("/", input).normalize();

System.out.printf("%s -> %s\n", input, path);

}

}

}

Output:

/foo -> /foo

//foo -> /foo

foo/ -> /foo

foo/bar -> /foo/bar

foo/bar/../baz -> /foo/baz

foo//bar -> /foo/bar

NOTE however that this is NOT portable. It won't work on Windows machines...

If you want a portable solution you can use memoryfilesystem, open a Unix filesystem and use that:

try (

final FileSystem fs = MemoryFileSystem.newLinux().build();

) {

// path operations here

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值