获取Java中的默认根目录

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

Getting the default root directory in Java

javafilebrowser

提问by Supuhstar

I'm making a basic file browser, and want to know how to get the default root directory. I know that java.io.File.listRoots()gives all the roots (for me it's A:\, C:\, D:\, E:\, F:\, G:\, H:\, I:\, L:\ T:\, U:\, X:\, Y:\, Z:\), but I want the one the user uses primarily (i.e. the one with the Operating system on it) so I know from where to start the browsing.

我正在制作一个基本的文件浏览器,并想知道如何获取默认根目录。我知道这java.io.File.listRoots()给出了所有的根源(对我来说是A:\, C:\, D:\, E:\, F:\, G:\, H:\, I:\, L:\ T:\, U:\, X:\, Y:\, Z:\),但我想要用户主要使用的那个(即上面有操作系统的那个),所以我知道从哪里开始浏览。

采纳答案by BullyWiiPlaza

Getting the operating system root partition is only a thing on Windowssince on Unixit's always /.

获取操作系统根分区只是一件事,Windows因为Unix它总是/.

Hence, the following code works for Windowsonly:

因此,以下代码Windows仅适用于:

System.getenv("SystemDrive");

It gets the SystemDriveenvironment variable value. This should always return the operating system's root partition e.g. C:.

它获取SystemDrive环境变量值。这应该总是返回操作系统的根分区,例如C:.

回答by btiernay

Not sure if this is of any help, but you could try:

不确定这是否有帮助,但您可以尝试:

import javax.swing.filechooser.*;

FileSystemView.getFileSystemView().getRoots()[0];

or

或者

FileSystemView.getFileSystemView().getHomeDirectory();

or

或者

System.getProperty("user.dir");

For the last snippet, you could get the root directory by navigating upward using getParent() until nullis returned.

对于最后一个片段,您可以通过使用 getParent() 向上导航来获取根目录,直到null返回为止。