Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.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_Algorithm_Filepath - Fatal编程技术网

Java:如何获取路径的各个部分

Java:如何获取路径的各个部分,java,algorithm,filepath,Java,Algorithm,Filepath,这应该是相当简单的,但我只是卡住了。假设您有路径/a/b/c/。我想将其转换为包含以下内容的数组: / /a/ /a/b/ /a/b/c/ 开头和结尾的斜杠应该是可选的。有人愿意帮忙吗 我将把它用于一个创建目录的函数,我希望它也能创建所有缺少的部分,并且在例如a或b不存在时不会失败 更新:如果可以的话,我当然会使用File.mkdirs(),但这不在本地文件系统上。这是为了简化与SFTP库的接口,该库只有一个采用字符串形式路径的mkdir方法。为什么不直接使用 编辑:根据您不使用File

这应该是相当简单的,但我只是卡住了。假设您有路径
/a/b/c/
。我想将其转换为包含以下内容的数组:

  • /
  • /a/
  • /a/b/
  • /a/b/c/
开头和结尾的斜杠应该是可选的。有人愿意帮忙吗

我将把它用于一个创建目录的函数,我希望它也能创建所有缺少的部分,并且在例如
a
b
不存在时不会失败


更新:如果可以的话,我当然会使用
File.mkdirs()
,但这不在本地文件系统上。这是为了简化与SFTP库的接口,该库只有一个采用字符串形式路径的
mkdir
方法。

为什么不直接使用


编辑:根据您不使用File.mkdirs()的要求:

我仍然认为使用
File
作为助手类更容易:

package com.example.test;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

public class FileSplitter {
    final private File path;

    public List<String> getPathStrings()
    {
        LinkedList<String> list = new LinkedList<String>();
        File p = this.path;
        while (p != null)
        {
            list.addFirst(p.getPath());
            p = p.getParentFile();
        }
        return list;
    }

    public FileSplitter(File path) { this.path = path; }

    public static void main(String[] args) {
        doit(new File("/foo/bar/baz"));
        doit(new File("/bam/biff/boom/pow"));
    }

    private static void doit(File file) {
        for (String s : new FileSplitter(file)
                .getPathStrings())
            System.out.println(s);      
    }
}
如果您无论如何都需要使用正向斜杠,那么我会使用字符串而不是文件来实现,或者在使用点上执行
.replace('\\','/')


最后,这里有一种可能对您的最终应用程序更有帮助的方法

它的输出与前一个相同,但有利于控制反转 在这里,您可以将自定义的
mkdir()
作为伪运行执行,并作为一个步骤传递给路径迭代器:

package com.example.test;

import java.io.File;

public class PathRunner
{
    final private File path;
    public PathRunner(File path) { 
        this.path = path; 
    }

    public interface Step
    {
        public boolean step(File path);
    }

    public boolean run(Step step) 
    {
        return run(step, this.path);
    }
    private boolean run(Step step, File p)
    {
        if (p == null)
            return true;
        else if (!run(step, p.getParentFile()))
            return false;
        else
            return step.step(p);
    }

    /**** test methods ****/

    public static void main(String[] args) {
        doit(new File("/foo/bar/baz"));
        doit(new File("/bam/biff/boom/pow"));
    }
    private static boolean doit(File path) {
        Step step = new Step()
        {
            @Override public boolean step(File path) {
                System.out.println(path);
                return true;
                /* in a mkdir operation, here's where you would call: 

                return yourObject.mkdir(
                    path.getPath().replace('\\', '/')
                );
                 */
            }               
        };
        return new PathRunner(path).run(step);
    }
}

没有必要这样做

这应该是一个相当简单的算法,如果给您一个字符串路径=“/a/b/c/”,您可以执行以下操作:

def f(st):
    index = 0
    array = []
    while index < len(st):
        if(st[index] == '/'):
            array += [st[:index+1]]

        index += 1
    return array
def(st):
索引=0
数组=[]
当指数
这是一个python算法,您可以轻松地将其转换为Java。当然,您可以使用Jason和I82经常指出的文件.mkdirs(),但了解算法的工作原理也很有趣

编辑 在Java中,不能对字符串进行迭代,但可以将该字符串转换为字符数组列表,迭代时,编写一个条件,如果字符为“/”,则创建一个新字符串,将从第一个到我们找到的当前字符(应为“/”)的所有字符连接在一起,并将其添加到先前初始化的字符串列表中。结果字符串列表将是您需要的列表。 如果你自己尝试,看看效果如何,这对你来说是一个很好的实践。当然,您可以迭代生成的列表并创建目录。

如果您需要一些基本内容。尝试拆分和追加。
File类支持这一点

public static void main(String... args) {
    split(new File("/a/b/c/d/e"));
    split(new File("\\A\\B\\C\\D\\E"));
}

private static void split(File file) {
    File parent = file.getParentFile();
    if (parent != null) split(parent);
    System.out.println(file);
}
关于windows打印

\
\a
\a\b
\a\b\c
\a\b\c\d
\a\b\c\d\e
\
\A
\A\B
\A\B\C
\A\B\C\D
\A\B\C\D\E

以以下代码结束:

   public String[] componizePath(String path)
   {
      ArrayList<String> parts = new ArrayList<String>();  

      int index = 0;
      while(index < path.length())
      {
         if(path.charAt(index) == '/' || index == path.length()-1)
         {
            parts.add(path.substring(0, index+1));
         }
         index++;
      }

      return parts.toArray(new String[0]);
   }

正如下面的两个答案一样,
File.mkdirs()
是前进的方向。然而,如果你真的坚持用手去做的话,
split(“/”)
将为您提供片段,您只需执行for循环:
String[]bits=path.split(“/”);文件f=null;对于(int i=0;我已经回答了为什么我不能使用它。首先应该提到的是,我的坏:9有点让它起作用了。但是它弄乱了斜线,这不是很好。部分。只是不相信它会保留潜在的开始斜线和结束斜线。如果可以避免的话,我也不想这样做:)什么是
array+=[st[:index+1]]
do?我假设它向数组中添加了另一个元素,但具体使用了什么?@Svish:st[:index+1]是一种python语法,它是从0到索引的字符串,例如,如果st=“abcdef”,那么st[:3]=“abc”。希望该帮助简单且似乎有效。如果开头或结尾没有
/
,该怎么办?据我所知,即使没有斜杠,它也会在结尾添加斜杠。@Svish您对拐角案例的看法是正确的,但此代码只是一个概念证明,可以为拐角案例提供帮助。您可以对其进行改进,也可以强制用户使用输入带有前导斜杠和尾随斜杠的路径。
public static void main(String... args) {
    split(new File("/a/b/c/d/e"));
    split(new File("\\A\\B\\C\\D\\E"));
}

private static void split(File file) {
    File parent = file.getParentFile();
    if (parent != null) split(parent);
    System.out.println(file);
}
\
\a
\a\b
\a\b\c
\a\b\c\d
\a\b\c\d\e
\
\A
\A\B
\A\B\C
\A\B\C\D
\A\B\C\D\E
   public String[] componizePath(String path)
   {
      ArrayList<String> parts = new ArrayList<String>();  

      int index = 0;
      while(index < path.length())
      {
         if(path.charAt(index) == '/' || index == path.length()-1)
         {
            parts.add(path.substring(0, index+1));
         }
         index++;
      }

      return parts.toArray(new String[0]);
   }
   @Test
   public void componizePath_EmptyPath()
   {
      String[] actual = getSftp().componizePath("");
      String[] expected = new String[0];
      assertArrayEquals(expected, actual);
   }

   @Test
   public void componizePath_RootPath()
   {
      String[] actual = getSftp().componizePath("/");
      String[] expected = new String[] {"/"};
      assertArrayEquals(expected, actual);
   }

   @Test
   public void componizePath_SimplePath()
   {
      String[] actual = getSftp().componizePath("a");
      String[] expected = new String[] {"a"};
      assertArrayEquals(expected, actual);
   }

   @Test
   public void componizePath_SimplePathWithTrailingSlash()
   {
      String[] actual = getSftp().componizePath("a/");
      String[] expected = new String[] {"a/"};
      assertArrayEquals(expected, actual);
   }

   @Test
   public void componizePath_ComplexerPath()
   {
      String[] actual = getSftp().componizePath("a/b/cc");
      String[] expected = new String[] {"a/", "a/b/", "a/b/cc"};
      assertArrayEquals(expected, actual);
   }

   @Test
   public void componizePath_ComplexerPathWithTrailingSlash()
   {
      String[] actual = getSftp().componizePath("a/b/c/");
      String[] expected = new String[] {"a/", "a/b/", "a/b/c/"};
      assertArrayEquals(expected, actual);
   }

   @Test
   public void componizePath_ComplexerPathWithLeadingSlash()
   {
      String[] actual = getSftp().componizePath("/a/b/c");
      String[] expected = new String[] {"/", "/a/", "/a/b/", "/a/b/c"};
      assertArrayEquals(expected, actual);
   }