我们如何从Java字符串中实际丢弃最后一个文件并仅获取文件路径目录?
用户输入的随机路径:
C:/my folder/tree/apple.exe
期望的输出:
C:/my folder/tree/
我找到的最接近的解决方案来自这里。这个论坛上的答案只显示获得的最后一个字符串,而不是其余的字符串。我想要显示其余的字符串。
最简单、最可靠(即跨平台)的解决方案是从路径创建一个 File
对象。
就像这样:
File myFile = new File( "C:/my folder/tree/apple.exe" );
// Now get the path
String myDir = myFile.getParent();
String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);
File
对象并不是在“制作文件”。它只是java.io函数的容器。 - mvreijn