仅获取路径目录并在 Java 中丢弃文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22141236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:51:41  来源:igfitidea点击:

Get path directory only and discard file in Java

javafile

提问by kkk

How do we actually discard last file from java string and just get the file path directory?

我们如何实际丢弃 java 字符串中的最后一个文件并只获取文件路径目录?

Random Path input by user:

用户输入的随机路径:

C:/my folder/tree/apple.exe

Desired output:

期望的输出:

C:/my folder/tree/

closest solution i found is from here. The answer from this forum only display last string acquired not the rest of it. I want to display the rest of the string.

我找到的最接近的解决方案来自这里。该论坛的答案仅显示获得的最后一个字符串,而不显示其余的字符串。我想显示字符串的其余部分。

采纳答案by mvreijn

The easiest and most failsafe (read: cross-platform) solution is to create a Fileobject from the path.

最简单和最安全的(阅读:跨平台)解决方案是File从路径创建一个对象。

Like this:

像这样:

File myFile = new File( "C:/my folder/tree/apple.exe" );
// Now get the path
String myDir = myFile.getParent();

回答by Florent Bayle

Try that:

试试看:

String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);