簡體   English   中英

Java:如何獲取路徑的各個部分

[英]Java: How to get the parts of a path

這應該很簡單,但我只是卡住了。 假設您有路徑/a/b/c/ 我想將其轉換為包含以下內容的數組:

  • /
  • /a/
  • /a/b/
  • /a/b/c/

開頭和結尾的斜線應該是可選的。 有人願意幫忙嗎?

我打算將它用於創建目錄的 function,並且我希望它也創建所有缺少的部分,並且在例如ab不存在時不會失敗。


更新:如果可以的話,我當然會使用File.mkdirs() ,但這不在本地文件系統上。 這是為了簡化與 SFTP 庫的接口,該庫只有一個mkdir方法,采用字符串形式的路徑。

為什么不直接使用File.mkdirs()


編輯:根據您的要求不要使用 File.mkdirs():

我仍然認為使用File作為助手 class 更容易:

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);      
    }
}

在我的機器(Windows)上打印出來:

\
\foo
\foo\bar
\foo\bar\baz
\
\bam
\bam\biff
\bam\biff\boom
\bam\biff\boom\pow

如果無論如何您都需要使用正斜杠,那么我要么使用字符串而不是文件來實現,要么只在使用點執行.replace('\\','/')


最后,這是一種可能對您的最終應用程序更有幫助的方法。

它具有與前一個相同的 output ,但有助於控制反轉,您可以在其中執行自定義mkdir()作為偽 Runnable 以作為路徑迭代器的一個步驟傳遞:

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);
    }
}

如果你需要一些原始的東西。 嘗試拆分和 append。

public class StackOverflow {

    public static void main(String args[]) {

        String[] folders = "/a/b/c/".split("/");
        String[] paths = new String[folders.length];
        String path = "";

        for (int i = 0; i < folders.length; i++) {
            path +=   folders[i] + "/";
            paths[i] = path;
        }
    }
}

這是代碼塊的output:

run:
/
/a/
/a/b/
/a/b/c/
BUILD SUCCESSFUL (total time: 0 seconds)

文件 class 支持這一點。

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]);
   }

JUnit 測試:

   @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);
   }

無需這樣做。 File.mkdirs() 代替

這應該是一個相當簡單的算法,如果給您一個字符串路徑 = "/a/b/c/",您可以執行以下操作:

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

        index += 1
    return array

這是一個 python 算法,您可以輕松地將其轉換為 Java。 當然,您可以使用 Jason 和 I82Much 指出的 File.mkdirs(),但看看算法是如何工作的也很有趣。

編輯在 Java 的情況下,您不能迭代字符串,但您可以將字符串轉換為字符的 arraylist,並且當您迭代時,您編寫條件,如果字符是“/”,則創建一個新字符串連接從第一個字符到當前我們找到的應該是“/”的所有字符,並將其添加到您之前初始化的字符串列表中。 生成的字符串列表將是您需要的列表。 如果您自己嘗試一下,看看效果如何,這對您來說是一個很好的做法。 當然,您可以遍歷結果列表並創建目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM