[英]Java, get full path of file and removing filename
I'm trying to get the directory path to a file. 我正在尝试获取文件的目录路径。 The issue I am having is getting the last
\\
or /
of the directory. 我遇到的问题是获取目录的最后一个
\\
或/
。 As this code is supposed to work on all operating systems, I can't seem to find any solution for this. 由于该代码应该在所有操作系统上都能工作,因此我似乎找不到任何解决方案。 Any help is appreciated.
任何帮助表示赞赏。
My code so far: 到目前为止,我的代码:
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);
My output is: 我的输出是:
PATH: C:\Users\User\Desktop\test\
PATH2: C:\Users\User\Desktop\test
This is just test code and not the real code I'm working on. 这只是测试代码,而不是我正在使用的真实代码。
EDIT What I'm trying to get is 编辑我想要得到的是
C:\Users\User\Desktop\test\
from 从
C:\Users\User\Desktop\test\test.txt
To get the absolute path to the parent directory you can do: 要获取父目录的绝对路径,您可以执行以下操作:
File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt");
String path = f.getParentFile().getAbsolutePath();
System.out.println(path);
Output: 输出:
C:\Users\User\Desktop\test
If you really want the trailing slash, then you can just append File.separator
: 如果您确实想要结尾的斜杠,则可以追加
File.separator
:
File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt ");
String path = f.getParentFile().getAbsolutePath() + File.separator;
System.out.println(path);
Output: 输出:
C:\Users\User\Desktop\test\
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.