Java有路径连接方法吗?

Geo*_*Geo 135 java file-io file path

完全重复:

在java中组合路径

我想知道Java中是否有这样的方法.以此片段为例:

// this will output a/b
System.out.println(path_join("a","b"));
// a/b 
System.out.println(path_join("a","/b");
Run Code Online (Sandbox Code Playgroud)

Dan*_*ant 165

这涉及Java版本7及更早版本.

同一个问题引用一个好的答案:

如果以后要将其作为字符串返回,可以调用getPath().实际上,如果你真的想模仿Path.Combine,你可以写下这样的东西:

public static String combine (String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}
Run Code Online (Sandbox Code Playgroud)

  • 不适用于Java 8.更好的选择:import java.nio.file.Paths; 路径路径= Paths.get(mydir,"myfile"); (30认同)
  • @MarcWittmann,在Java 8中执行此操作会发生什么? (12认同)
  • 使用Java 7的nio解决方案要短得多:`Paths.get(path1,path2)` (9认同)

Pet*_*rey 102

你可以这样做

String joinedPath = new File(path1, path2).toString();
Run Code Online (Sandbox Code Playgroud)

  • 不会``getPath()`或`getAbsolutePath()`比`toString()`更好? (35认同)
  • 供将来参考:`toString()`与File类的`getPath()`相同. (7认同)
  • @fstanis:与`toString()`相比,``getPath()`更具可读性(假设它们返回相同的东西) (2认同)