Java 移动到下一级目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9677541/
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-16 06:02:30  来源:igfitidea点击:

Moving to a directory one level down

javapath

提问by sutoL

Is it possible to move to a directory one level down in Java?

是否可以在 Java 中移动到下一级目录?

For example in command prompt:

例如在命令提示符中:

C:\Users\foo\

I can use cd..to go to:

我可以cd..用来去:

C:\Users\

Is it possible to do this in Java, because I'm getting a directory using System.getProperty("user.dir"); however that is not the directory I'd want to work at, but rather 1 level down the directory.

是否可以在 中执行此操作Java,因为我使用 System.getProperty("user.dir"); 获取目录;然而,这不是我想要工作的目录,而是目录下一级。

I have thought of using the Path class method; subpath(i,j), but if the "user.dir" were to be changed to another directory, then the returned subpathwould be different.

曾经想过使用Path类的方法;subpath(i,j),但如果将“user.dir”更改为另一个目录,则返回的subpath将不同。

采纳答案by sethcall

The File class can do this natively.

File 类可以本机执行此操作。

File upOne = new File(System.getProperty("user.dir")).getParentFile()

http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getParentFile%28%29

http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getParentFile%28%29

回答by Java42

On my system, the ".." is a valid component of a path.
Here is an example.

在我的系统上,“..”是路径的有效组成部分。
这是一个例子。

File file;
String userDir = System.getProperty("user.dir");
file = new File(userDir);
System.out.println(file.getCanonicalPath());
file = new File(userDir+"/..");
System.out.println(file.getCanonicalPath());

Output is:

输出是:

C:\anog\workaces\_JAV_1.0.0\CODE_EXAMPLE
C:\anog\workaces\_JAV_1.0.0

回答by ig0774

As the previous answers have pointed out, you can do this using File. Alternatively, using the Java 7 NIO classes, as you appear to be doing, the following should do the same:

正如前面的答案所指出的,您可以使用File. 或者,使用 Java 7 NIO 类,正如您所做的那样,以下应该做同样的事情:

Paths.get(System.getProperty("user.dir") + "/..").toRealPath();

Note that "/" is a valid directory separator on the Windows file system as well (though I tested this code on Linux).

请注意,“/”也是 Windows 文件系统上的有效目录分隔符(尽管我在 Linux 上测试了此代码)。

回答by Sushila Jyothi Lévêque

private static void downDir(int levels) {
    String oldPath = System.getProperty("user.dir");
    String[] splitedPathArray = oldPath.split("/");
    levels = splitedPathArray.length - levels;
    List<String> splitedPathList = Arrays.asList(splitedPathArray);
    splitedPathList = splitedPathList.subList(0, levels);
    String newPath = String.join("/", splitedPathList);
    System.setProperty("user.dir", newPath);
}

Should work. For the levels, just specify 1.

应该管用。对于级别,只需指定 1。