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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:57:31  来源:igfitidea点击:

Create a Path from String in Java7

stringpathniojava-7

提问by mat_boy

How can I create a java.nio.file.Pathobject from a Stringobject in Java 7?

如何java.nio.file.PathStringJava 7 中的对象创建对象?

I.e.

IE

String textPath = "c:/dir1/dir2/dir3";
Path path = ?;

where ?is the missing code that uses textPath.

哪里?是遗漏码使用textPath

回答by Jon Skeet

You can just use the Pathsclass:

你可以只使用这个Paths类:

Path path = Paths.get(textPath);

... assuming you want to use the default file system, of course.

...当然,假设您想使用默认文件系统。

回答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 Pathdirectly 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 Pathclass 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");