英文:
What kinds of type is better for get the path String?
问题
我想获取有关路径的字符串值。
我有两种方法。
- 使用String.format()
String a = "/root";
String b = "Downloads";
String path = String.format("%s/%s", a, b);
- 使用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.
- Using String.format()
String a = "/root"
String b = "Downloads"
String path = String.format("%s/%s",a,b)
- 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", "bPaths.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", "bPaths.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论