Java,获取文件的完整路径并删除文件名

问题描述 投票:0回答:2

我正在尝试获取文件的目录路径。我遇到的问题是获取目录的最后一个

\
/
。由于此代码应该适用于所有操作系统,因此我似乎找不到任何解决方案。如有任何帮助,我们将不胜感激。

到目前为止我的代码:

System.out.print("Enter dir: ");
String path = kb.nextLine();
File pathes = new File(path);
String path2 = pathes.getParent();
path = path.substring(0, path.lastIndexOf("\\")+1);
System.out.println("PATH: " + path);
System.out.println("PATH2: "+path2);

我的输出是:

PATH: C:\Users\User\Desktop\test\
PATH2: C:\Users\User\Desktop\test

这只是测试代码,而不是我正在处理的真实代码。

编辑 我想要得到的是

C:\Users\User\Desktop\test\

来自

C:\Users\User\Desktop\test\test.txt
java file path apache-commons
2个回答
4
投票

要获取父目录的绝对路径,您可以执行以下操作:

File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt");
String path = f.getParentFile().getAbsolutePath();
System.out.println(path);

输出:

C:\Users\User\Desktop\test

如果您真的想要尾部斜线,那么您只需附加

File.separator

File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt ");
String path = f.getParentFile().getAbsolutePath() + File.separator;
System.out.println(path);

输出:

C:\Users\User\Desktop\test\

0
投票

当 File 对象没有路径时,即它只是一个文件名时,前面的答案会给出 NullPointerException。

稍作修改也适用于这种情况

File file1 = ... // as before
File file2 = new File(file1.getCanonicalPath());
String path = file2.getParentFile().getCanonicalPath();
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.