Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中组合路径?_Java_Path - Fatal编程技术网

如何在Java中组合路径?

如何在Java中组合路径?,java,path,Java,Path,在C#/.NET中是否有Java等价物?或者任何代码来实现这一点 此静态方法将一个或多个字符串组合到一个路径中。您应该使用一个用于表示文件系统路径的类,而不是将所有内容都基于字符串 如果使用java 7或java 8,则应该强烈地考虑使用;代码>路径。解析可用于将一条路径与另一条路径或字符串组合。helper类也很有用。例如: Path path = Paths.get("foo", "bar", "baz.txt"); 如果您需要适应Java-7之前的环境,您可以使用: File baseD

在C#/.NET中是否有Java等价物?或者任何代码来实现这一点


此静态方法将一个或多个字符串组合到一个路径中。

您应该使用一个用于表示文件系统路径的类,而不是将所有内容都基于字符串

如果使用java 7或java 8,则应该强烈地考虑使用;代码>路径。解析可用于将一条路径与另一条路径或字符串组合。helper类也很有用。例如:

Path path = Paths.get("foo", "bar", "baz.txt");
如果您需要适应Java-7之前的环境,您可以使用:

File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
如果您希望以后将其作为字符串返回,可以调用
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();
}
/hello/world/warez.lha

主要的答案是使用文件对象。但是有一个类可以做这种事情,比如方法。

为了增强JodaStephen的回答,ApacheCommonsIO有一个FilenameUtils来做这件事。示例(在Linux上):


它独立于平台,将产生系统所需的任何分离器。

这里有一个解决方案,可处理多路径部件和边缘条件:

public static String combinePaths(String ... paths)
{
  if ( paths.length == 0)
  {
    return "";
  }

  File combined = new File(paths[0]);

  int i = 1;
  while ( i < paths.length)
  {
    combined = new File(combined, paths[i]);
    ++i;
  }

  return combined.getPath();
}
公共静态字符串组合路径(字符串…路径)
{
if(path.length==0)
{
返回“”;
}
文件组合=新文件(路径[0]);
int i=1;
while(i
我知道Jon的原始答案已经很久了,但我对OP有类似的要求

通过扩展Jon的解决方案,我提出了以下方法,即使用一个或多个路径段,使用尽可能多的路径段

用法

Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });
这里为其他有类似问题的人编码

public class Path {
    public static String combine(String... paths)
    {
        File file = new File(paths[0]);

        for (int i = 1; i < paths.length ; i++) {
            file = new File(file, paths[i]);
        }

        return file.getPath();
    }
}
公共类路径{
公共静态字符串组合(字符串…路径)
{
文件=新文件(路径[0]);
for(int i=1;i
在Java 7中,您应该使用:

虽然NIO2 Path类对于使用不必要的不同API的文件来说似乎有点多余,但实际上它更优雅、更健壮

请注意,
Path.get()
(根据其他人的建议)没有重载获取
Path
,执行
Path.get(Path.toString(),childPath)
resolve()
不同。从:

请注意,虽然此方法非常方便,但使用它将意味着对默认文件系统的假定引用,并限制调用代码的实用性。因此,不应在旨在灵活重用的库代码中使用它。更灵活的替代方法是使用现有路径实例作为锚点,例如:

Path dir = ...
Path path = dir.resolve("file");
解析
的姐妹函数是最优秀的:


如果只需要字符串,则可以使用

得到

"some/prefix/with/extra/slashes/file/name"

独立于平台的方法(使用File.separator,ie是否有效取决于运行代码的操作系统:

java.nio.file.Paths.get(".", "path", "to", "file.txt")
// relative unix path: ./path/to/file.txt
// relative windows path: .\path\to\filee.txt

java.nio.file.Paths.get("/", "path", "to", "file.txt")
// absolute unix path: /path/to/filee.txt
// windows network drive path: \\path\to\file.txt

java.nio.file.Paths.get("C:", "path", "to", "file.txt")
// absolute windows path: C:\path\to\file.txt

可能会迟到,但我想分享我对这一点的看法。我正在使用一个构建器模式,并允许方便地链接
append(更多)
调用,并允许混合
文件
字符串
。它可以很容易地扩展,以支持使用
路径
对象,并且在Linux、Macintosh等上正确处理不同的路径分隔符

public class Files  {
    public static class PathBuilder {
        private File file;

        private PathBuilder ( File root ) {
            file = root;
        }

        private PathBuilder ( String root ) {
            file = new File(root);
        }

        public PathBuilder append ( File more ) {
            file = new File(file, more.getPath()) );
            return this;
        }

        public PathBuilder append ( String more ) {
            file = new File(file, more);
            return this;
        }

        public File buildFile () {
            return file;
        }
    }

    public static PathBuilder buildPath ( File root ) {
        return new PathBuilder(root);
    }

    public static PathBuilder buildPath ( String root ) {
        return new PathBuilder(root);
    }
}
用法示例:

File root = File.listRoots()[0];
String hello = "hello";
String world = "world";
String filename = "warez.lha"; 

File file = Files.buildPath(root).append(hello).append(world)
              .append(filename).buildFile();
String absolute = file.getAbsolutePath();
生成的
绝对值
将包含以下内容:

public static String combine(String path1, String path2)
{
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}
/hello/world/warez.lha
甚至可能:

A:\hello\world\warez.lha

这也适用于Java 8:

Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");

此解决方案提供了一个接口,用于连接字符串[]数组中的路径片段。它使用java.io.File.File(字符串父级,字符串子级)

    public static joinPaths(String[] fragments) {
        String emptyPath = "";
        return buildPath(emptyPath, fragments);
    }

    private static buildPath(String path, String[] fragments) {
        if (path == null || path.isEmpty()) {
            path = "";
        }

        if (fragments == null || fragments.length == 0) {
            return "";
        }

        int pathCurrentSize = path.split("/").length;
        int fragmentsLen = fragments.length;

        if (pathCurrentSize <= fragmentsLen) {
            String newPath = new File(path, fragments[pathCurrentSize - 1]).toString();
            path = buildPath(newPath, fragments);
        }

        return path;
    }
返回:

"/dir/anotherDir/filename.txt"


假设所有给定的路径都是绝对路径。您可以按照下面的代码片段合并这些路径

String baseURL = "\\\\host\\testdir\\";
String absoluteFilePath = "\\\\host\\testdir\\Test.txt";;
String mergedPath = Paths.get(baseURL, absoluteFilePath.replaceAll(Matcher.quoteReplacement(baseURL), "")).toString();

输出路径为\\host\testdir\Test.txt。

注意绝对路径。NET版本将返回
path2
(忽略
path1
)如果
path2
是一个绝对路径,Java版本将删除前导的
/
\
,并将其视为一个相对路径。@Hugo:所以它浪费了整整两个对象?令人震惊!老实说,在我看来,它相当干净……它将相对文件名的逻辑保留在它所属的文件类中。尽管如此,我还是认为structor
新文件(String…pathElements)
会更干净,可以添加一个
新文件(File basepath,String…pathElements)
@modosansreves:看看
文件。getCanonicalPath
@SargeBorsch:C只是一种语言。如果你愿意的话,你可以轻松地在C中创建自己的
文件。(我想你的意思是,
文件的存在是一个好处,我同意。)确切地说,FilenameUtils.concat。如果你使用类似JSF的东西,你肯定会希望它基于字符串,因为你得到的所有路径都是基于字符串的。所以这个问题可能会有所帮助。
String[] fragments = {"dir", "anotherDir/", "/filename.txt"};
String path = joinPaths(fragments);
"/dir/anotherDir/filename.txt"

String baseURL = "\\\\host\\testdir\\";
String absoluteFilePath = "\\\\host\\testdir\\Test.txt";;
String mergedPath = Paths.get(baseURL, absoluteFilePath.replaceAll(Matcher.quoteReplacement(baseURL), "")).toString();