什么类型更适合获取路径字符串?

huangapple go评论67阅读模式
英文:

What kinds of type is better for get the path String?

问题

我想获取有关路径的字符串值。

我有两种方法。

  1. 使用String.format()
String a = "/root";
String b = "Downloads";
String path = String.format("%s/%s", a, b);
  1. 使用Paths.get()
String a = "/root";
String b = "Downloads";
String path = Paths.get(a, b).toString();

哪种方法更好?
或者
您有更好的实践吗?

英文:

I want to get the String value about path.

I have two way about that.

  1. Using String.format()
String a = "/root"
String b = "Downloads"    
String path = String.format("%s/%s",a,b)
  1. Using Paths.get()
String a = "/root"
String b = "Downloads"    
String path = Path.get(a,b).toString();

Which one is better?
or
Do you have more better practice?

答案1

得分: 2

Paths.get 验证你传入的文件路径在语法上是有效的。例如,在Unix上,如果你执行以下操作:

Paths.get("a", "b
Paths.get("a", "b\000") // -> java.nio.file.InvalidPathException: Nul character not allowed
0") // -> java.nio.file.InvalidPathException: Nul character not allowed

它还会去除额外的目录分隔符:

Paths.get("a/", "/b") // -> a/b

如果这种行为是你想要的,请使用 Paths.get

如果你只想进行拼接而没有额外的检查,请使用 String.format

英文:

Paths.get verifies that you pass in syntactically valid file paths. For example, on Unix you get an exception from:

Paths.get("a", "b
Paths.get("a", "b\000") // -> java.nio.file.InvalidPathException: Nul character not allowed
0") // -> java.nio.file.InvalidPathException: Nul character not allowed

It also gets rid of extra directory separators:

Paths.get("a/", "/b") // -> a/b

If this behavior is what you want, use Paths.get.

If you just want to concatenate with no extra checks, use String.format.

答案2

得分: 0

最适合处理路径的工具是:

import java.nio.file.*;
// 示例 1
Path p = Paths.get("/articles/folder");
// 示例 2
Path p2 = Paths.get("/articles", "folder");

更多信息请参阅Path文档

英文:

Best util for path is:

import java.nio.file.*;
// Example 1
Path p = Paths.get("/articles/folder");
// Example 2
Path p2 = Paths.get("/articles", "folder");

For more info see Path Documentation

huangapple
  • 本文由 发表于 2020年8月10日 10:17:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63333274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定