string 在 Java7 中从字符串创建路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16919501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a Path from String in Java7
提问by mat_boy
How can I create a java.nio.file.Path
object from a String
object in Java 7?
如何java.nio.file.Path
从String
Java 7 中的对象创建对象?
I.e.
IE
String textPath = "c:/dir1/dir2/dir3";
Path path = ?;
where ?
is the missing code that uses textPath
.
哪里?
是遗漏码使用textPath
。
回答by Jon Skeet
回答by Karthik Karuppannan
From the javadocs..http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
从 javadocs .. http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Path p1 = Paths.get("/tmp/foo");
is the same as
是相同的
Path p4 = FileSystems.getDefault().getPath("/tmp/foo");
Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log");
In Windows, creates file C:\joe\logs\foo.log (assuming user home as C:\joe)
In Unix, creates file /u/joe/logs/foo.log (assuming user home as /u/joe)
在 Windows 中,创建文件 C:\joe\logs\foo.log(假设用户 home 为 C:\joe)
在 Unix 中,创建文件 /u/joe/logs/foo.log(假设用户 home 为 /u/joe)
回答by sevenforce
If possible I would suggest creating the Path
directly from the path elements:
如果可能,我建议Path
直接从路径元素创建:
Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\dir1\dir2\dir3"
回答by Arcones
Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path
class that allows to do this straight away:
即使问题是关于 Java 7 的,我认为知道从 Java 11 开始,类中有一个静态方法Path
可以立即执行此操作,这会增加价值:
With all the path in one String:
在一个字符串中包含所有路径:
Path.of("/tmp/foo");
Path.of("/tmp/foo");
With the path broken down in several Strings:
路径分解为几个字符串:
Path.of("/tmp","foo");
Path.of("/tmp","foo");