在Java中创建路径的速记方法是什么?

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

Shorthand to create a path in Java?

问题

我有一个代码示例,可以创建如下路径:

    String path = System.getProperty("user.dir") + File.separator + "games" + File.separator + "game.exe";

重复输入File.separator很繁琐且困难。是否有一种更简短的方式来创建路径?我创建了一个自定义函数来实现,但不确定是否正确。请提供建议。

//例如 getPath("downloads", "games", "racing.exe") ---> \downloads\games\racing.exe
public static String getPath(String... pathFragments){
    StringBuilder sb = new StringBuilder(File.separator);

    for(int i = 0; i < pathFragments.length-1; i++){
        sb.append(pathFragments[i] + File.separator);
    }

    //添加最后一个 pathFragment。
    sb.append(pathFragments[pathFragments.length-1]);

    return sb.toString();
}
英文:

I have a code example which creates paths like this :

    String path = System.getProperty(&quot;user.dir&quot;) + File.separator + &quot;games&quot; + File.separator + &quot;game.exe&quot;;

It is irritating and difficult to type File.separator repeatedly. Is there a shorter way to create the path ? I created a custom function to do that, but I am not sure if it is the right way. Please advise.

//Ex. getPath(&quot;downloads&quot;, &quot;games&quot;, &quot;racing.exe&quot;) ---&gt; \downloads\games\racing.exe
public static String getPath(String...pathFragments){
    StringBuilder sb = new StringBuilder(File.separator);

    for(int i = 0; i &lt; pathFragments.length-1; i++){
        sb.append(pathFragments[i] + File.separator);
    }

    //Append last pathFragment.
    sb.append(pathFragments[pathFragments.length-1]);

    return sb.toString();
}

答案1

得分: 4

First thought: 为什么还要使用File.separator呢?直接使用跨平台的系统无关文件分隔符/即可。

String path = System.getProperty("user.dir") + "/games/game.exe";

唯一需要使用File.separator的情况是,如果你正在构建用于用户界面的文件路径,并且想要将路径字符串显示给用户,不想在路径中混合使用 / 和 \ 以避免让Windows用户困惑。

Second thought: 除非你有充分的理由使用字符串,否则请使用Paths.get。充分的理由包括与古老版本的Java或库保持向后兼容。

// 你可能不需要添加System.getProperty("user.dir")
// 相对路径会根据当前工作目录解析
Path path = Paths.get("games/game.exe");

Third thought: 使用String.join代替StringBuilder.append

public static String getPath(String... pathFragments) {
    return File.separator + String.join(File.separator, pathFragments);
}
英文:

First thought: Why do you bother with File.separator? Use the cross-platform system-independent file separator character / instead.

String path = System.getProperty(&quot;user.dir&quot;) + &quot;/games/game.exe&quot;;

The only use for File.separator is if you are constructing a file path for a user interface, and want to show the path string to the user, and don't want to confuse Windows users by mixing / and \ in the path.

Second thought: Unless you have a compelling reason to work with Strings, use Paths.get. Compelling reasons include staying backwards compatible with ancient versions of Java or libraries.

// You probably don&#39;t need to add System.getProperty(&quot;user.dir&quot;)
// Relative paths are resolved against current working directory
Path path = Paths.get(&quot;games/game.exe&quot;);

Third thought: Use String.join instead of StringBuilder.append

public static String getPath(String... pathFragments) {
    return File.separator + String.join(File.separator, pathFragments);
}

答案2

得分: 1

String[] leafs = { "games", "game.exe" };
String path = makePath("user.dir", File.separator, leafs);
// or
String path = makePath("user.dir", File.separator, "games", "game.exe");
System.out.println(path);
	
	
public static String makePath(String property, String separator, String... leafs) {
    return System.getProperty(property) + File.separator 
            + String.join(File.separator, leafs);
}
英文:
String[] leafs = { &quot;games&quot;, &quot;game.exe&quot; };
String path = makePath(&quot;user.dir&quot;, File.separator, leafs);
// or
String path = makePath(&quot;user.dir&quot;, File.separator, &quot;games&quot;, &quot;game.exe&quot;);
System.out.println(path);
	
	
public static String makePath(String property,String separator, String... leafs) {
	    return System.getProperty(property) + File.separator 
	            + String.join(File.separator, leafs);
}
	

</details>



# 答案3
**得分**: 1

你不需要一个函数,一旦你使用了 `File` 或者 `Path`,那么 `File.separator` 应该很少被使用。例如,`Path.of()` 是你所需要的全部:

```java
Path path = Path.of(System.getProperty("user.dir"), "games", "game.exe");
System.out.println("path=" + path);

一些示例使用 Paths.get(),但实际上它只是调用了 Path.of()。注意,Paths.of() 适用于 JDK11+,而 Paths.get() 适用于 JDK7+。

英文:

You don't need a function, and once you use File or Path then File.separator should be rarely used. For example Path.of() is all you need:

Path path = Path.of(System.getProperty(&quot;user.dir&quot;), &quot;games&quot;, &quot;game.exe&quot;);
System.out.println(&quot;path=&quot;+path);

Some examples use Paths.get() but that just calls Path.of(). Note that Paths.of() is for JDK11+, but Paths.get() is JDK7+.

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

发表评论

匿名网友

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

确定