【问题标题】:split string (full path to file)拆分字符串(文件的完整路径)
【发布时间】:2014-05-11 10:55:40
【问题描述】:

我有一个字符串 = "/dir1/dir2/file1.sth"

String = "/dir1/file2.sth"

和其他。

我需要这样做:

路径:/dir1/dir2/

文件名:file1.sth

在 Java 中如何做到这一点?

【问题讨论】:

  • 简单,通过编写代码。
  • 找到/的最后一个索引并从那里拆分。
  • 找到最后一个'/'的索引并将其用作分割的边界?
  • 好吧,因为有路径操作的功能,例如Python 我不明白为什么这个问题会受到反对和讽刺的 cmets
  • thx 我知道该怎么做,但这是个错误的问题。我不知道功能:) 谢谢。

标签: java string split


【解决方案1】:

根据字符串创建一个文件对象。然后您可以调用 getName() 来获取名称。你可以调用 getParent() 来获取它之前的路径

请参阅以下文档:docs.oracle.com/javase/7/docs/api/java/io/File.html

【讨论】:

    【解决方案2】:

    如果您使用该路径(/dir1/file2.sth)定义一个文件对象,您可以轻松拆分文件名和地址:

    File f=new File("/dir1/file2.sth");
    
    //get file name
    f.getName();
    
    //get path
    f.getParentFile();
    

    【讨论】:

      【解决方案3】:
      public static void main(String[] args) {
          String filePath = "/dir1/dir2/file1.sth";
          String[] components = filePath.split("/");
      
          String path = "";
          for (int i = 0; i < components.length-1; i++)
          {
             path += components[i] + "/";
          }
          String file = components[components.length-1];
      
          System.out.println("Path name: " + path);
          System.out.println("File name: " + file);
      }
      

      这会得到你想要的,它还会显示输出。

      【讨论】:

        猜你喜欢
        • 2018-10-27
        • 2015-02-15
        • 2019-09-28
        • 2012-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多