下面列出了java.io.File#listRoots ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @param key a <code>String</code>
* "fileChooserDefaultFolder":
* Returns a <code>File</code> - the default shellfolder for a new filechooser
* "roots":
* Returns a <code>File[]</code> - containing the root(s) of the displayable hierarchy
* "fileChooserComboBoxFolders":
* Returns a <code>File[]</code> - an array of shellfolders representing the list to
* show by default in the file chooser's combobox
* "fileChooserShortcutPanelFolders":
* Returns a <code>File[]</code> - an array of shellfolders representing well-known
* folders, such as Desktop, Documents, History, Network, Home, etc.
* This is used in the shortcut panel of the filechooser on Windows 2000
* and Windows Me.
* "fileChooserIcon <icon>":
* Returns an <code>Image</code> - icon can be ListView, DetailsView, UpFolder, NewFolder or
* ViewMenu (Windows only).
*
* @return An Object matching the key string.
*/
public Object get(String key) {
if (key.equals("fileChooserDefaultFolder")) {
// Return the default shellfolder for a new filechooser
File homeDir = new File(System.getProperty("user.home"));
try {
return createShellFolder(homeDir);
} catch (FileNotFoundException e) {
return homeDir;
}
} else if (key.equals("roots")) {
// The root(s) of the displayable hierarchy
return File.listRoots();
} else if (key.equals("fileChooserComboBoxFolders")) {
// Return an array of ShellFolders representing the list to
// show by default in the file chooser's combobox
return get("roots");
} else if (key.equals("fileChooserShortcutPanelFolders")) {
// Return an array of ShellFolders representing well-known
// folders, such as Desktop, Documents, History, Network, Home, etc.
// This is used in the shortcut panel of the filechooser on Windows 2000
// and Windows Me
return new File[] { (File)get("fileChooserDefaultFolder") };
}
return null;
}
public List<String> getPossibleSteamFolders()
throws CharConversionException,
InfinitiveLoopException {
String folderList = ini.getKeyValue("/", CONFIG_STEAM_FOLDERS, CONFIG_STEAM_FOLDERS__POSSIBLE_DIRS);
String[] patterns = folderList.split(Matcher.quoteReplacement(";"), 0);
List<String> allSteamPaths = new ArrayList<>(80);
File[] roots = File.listRoots();
String[] driveLetters = new String[roots.length];
for (int nRoot = 0; nRoot < roots.length; nRoot++) {
driveLetters[nRoot] = roots[nRoot].getAbsolutePath();
}
String varDriveLetter = /* Matcher.quoteReplacement( */ "{drive_letter}"/* ) */;
for (String basePattern : patterns) {
for (String driveLetter : driveLetters) {
allSteamPaths.add(basePattern.replace(varDriveLetter, driveLetter));
}
}
Collections.addAll(allSteamPaths, patterns);
return allSteamPaths;
}
public static List<String> findBrowsersInProgramFiles() {
// find possible root
File[] rootPaths = File.listRoots();
List<String> browsers = new ArrayList<>();
String[] defaultPath = (is64bit)
? new String[] {
"Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"Program Files (x86)\\Internet Explorer\\iexplore.exe",
"Program Files (x86)\\Mozilla Firefox\\firefox.exe" }
: new String[] {
"Program Files\\Google\\Chrome\\Application\\chrome.exe",
"Program Files\\Internet Explorer\\iexplore.exe",
"Program Files\\Mozilla Firefox\\firefox.exe" };
// check file existence
for (File rootPath : rootPaths) {
for (String defPath : defaultPath) {
File exe = new File(rootPath + defPath);
if (debug)
System.err.println("Inspecting browser path: " + rootPath + defPath);
if (exe.exists())
browsers.add(exe.toString());
}
}
return browsers;
}
/**
* Initialize the Tree with the filesystem
*/
private void initTree() {
RootTreeNode root = new RootTreeNode(executorService);
for (File f : File.listRoots()) {
root.add(new FilesystemTreeNode(f));
}
model = new DefaultTreeModel(root);
// to fire change event when the loading is finished
root.setModel(model);
tree = new JTree(model);
tree.addTreeSelectionListener(selectionListener);
tree.addTreeExpansionListener(expansionListener);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.expandRow(0);
tree.setRootVisible(false);
tree.setCellRenderer(new FileTreeCellRenderer());
}
@Override
public void goUp() {
if (currentDir == null)
return;
File parent = currentDir.getParentFile();
if (parent == null) {
currentDir = null;
files.clear();
File[] a = File.listRoots();
if (a == null)
return;
for (File file : a) {
if (!fsv.isDrive(file) || fsv.getSystemDisplayName(file).isEmpty())
continue;
files.add(file);
}
selectedFile = files.isEmpty() ? -1 : 0;
return;
}
updateDir(parent);
}
@Override
public void goUp() {
if (currentDir == null)
return;
File parent = currentDir.getParentFile();
if (parent == null) {
currentDir = null;
files.clear();
File[] a = File.listRoots();
if (a == null)
return;
for (File file : a) {
if (!fsv.isDrive(file) || fsv.getSystemDisplayName(file).isEmpty())
continue;
files.add(file);
}
selectedFile = files.isEmpty() ? -1 : 0;
return;
}
updateDir(parent);
}
public void run(){
while(isActive()){
try{
Thread.sleep(samplingRate);
}catch (InterruptedException e){
logger.error(e.getMessage(), e);
}
roots = File.listRoots();
long totalFreeSpace = 0;
for (int i = 0; i < roots.length; i++) {
totalFreeSpace += roots[i].getFreeSpace();
}
//convert to MB
totalFreeSpace = totalFreeSpace / (1024 * 1024);
StreamElement streamElement = new StreamElement(new String[]{"FREE_SPACE"}, new Byte[]{DataTypes.BIGINT}, new Serializable[] {totalFreeSpace
},System.currentTimeMillis());
postStreamElement(streamElement);
}
}
@Test
public void requireCommonBaseDirNoCommon() {
final File[] fileSystemRoots = File.listRoots();
if (fileSystemRoots.length == 1) {
// single file system root isn't what we are interested in, in this test method
return;
}
// we expect a BuildException when we try to find a (non-existent) common base dir
// across file system roots
expExc.expect(BuildException.class);
List<ArtifactDownloadReport> reports = Arrays.asList(
artifactDownloadReport(new File(fileSystemRoots[0], "a/b/c/d")),
artifactDownloadReport(new File(fileSystemRoots[1], "a/b/e/f"))
);
fileset.requireCommonBaseDir(reports);
}
/**
* @param key a <code>String</code>
* "fileChooserDefaultFolder":
* Returns a <code>File</code> - the default shellfolder for a new filechooser
* "roots":
* Returns a <code>File[]</code> - containing the root(s) of the displayable hierarchy
* "fileChooserComboBoxFolders":
* Returns a <code>File[]</code> - an array of shellfolders representing the list to
* show by default in the file chooser's combobox
* "fileChooserShortcutPanelFolders":
* Returns a <code>File[]</code> - an array of shellfolders representing well-known
* folders, such as Desktop, Documents, History, Network, Home, etc.
* This is used in the shortcut panel of the filechooser on Windows 2000
* and Windows Me.
* "fileChooserIcon <icon>":
* Returns an <code>Image</code> - icon can be ListView, DetailsView, UpFolder, NewFolder or
* ViewMenu (Windows only).
*
* @return An Object matching the key string.
*/
public Object get(String key) {
if (key.equals("fileChooserDefaultFolder")) {
// Return the default shellfolder for a new filechooser
File homeDir = new File(System.getProperty("user.home"));
try {
return createShellFolder(homeDir);
} catch (FileNotFoundException e) {
return homeDir;
}
} else if (key.equals("roots")) {
// The root(s) of the displayable hierarchy
return File.listRoots();
} else if (key.equals("fileChooserComboBoxFolders")) {
// Return an array of ShellFolders representing the list to
// show by default in the file chooser's combobox
return get("roots");
} else if (key.equals("fileChooserShortcutPanelFolders")) {
// Return an array of ShellFolders representing well-known
// folders, such as Desktop, Documents, History, Network, Home, etc.
// This is used in the shortcut panel of the filechooser on Windows 2000
// and Windows Me
return new File[] { (File)get("fileChooserDefaultFolder") };
}
return null;
}
public void testValidRoots () throws Exception {
assertNotNull(testedFS.getRoot());
assertTrue(testedFS.getRoot().isValid());
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = File.listRoots();
boolean validRoot = false;
for (int i = 0; i < roots.length; i++) {
FileObject root1 = FileUtil.toFileObject(roots[i]);
if (!roots[i].exists()) {
assertNull(root1);
continue;
}
assertNotNull(roots[i].getAbsolutePath (),root1);
assertTrue(root1.isValid());
if (testedFS == root1.getFileSystem()) {
validRoot = true;
}
}
assertTrue(validRoot);
}
/**
* @param key a <code>String</code>
* "fileChooserDefaultFolder":
* Returns a <code>File</code> - the default shellfolder for a new filechooser
* "roots":
* Returns a <code>File[]</code> - containing the root(s) of the displayable hierarchy
* "fileChooserComboBoxFolders":
* Returns a <code>File[]</code> - an array of shellfolders representing the list to
* show by default in the file chooser's combobox
* "fileChooserShortcutPanelFolders":
* Returns a <code>File[]</code> - an array of shellfolders representing well-known
* folders, such as Desktop, Documents, History, Network, Home, etc.
* This is used in the shortcut panel of the filechooser on Windows 2000
* and Windows Me.
* "fileChooserIcon <icon>":
* Returns an <code>Image</code> - icon can be ListView, DetailsView, UpFolder, NewFolder or
* ViewMenu (Windows only).
*
* @return An Object matching the key string.
*/
public Object get(String key) {
if (key.equals("fileChooserDefaultFolder")) {
// Return the default shellfolder for a new filechooser
File homeDir = new File(System.getProperty("user.home"));
try {
return createShellFolder(homeDir);
} catch (FileNotFoundException e) {
return homeDir;
}
} else if (key.equals("roots")) {
// The root(s) of the displayable hierarchy
return File.listRoots();
} else if (key.equals("fileChooserComboBoxFolders")) {
// Return an array of ShellFolders representing the list to
// show by default in the file chooser's combobox
return get("roots");
} else if (key.equals("fileChooserShortcutPanelFolders")) {
// Return an array of ShellFolders representing well-known
// folders, such as Desktop, Documents, History, Network, Home, etc.
// This is used in the shortcut panel of the filechooser on Windows 2000
// and Windows Me
return new File[] { (File)get("fileChooserDefaultFolder") };
}
return null;
}
/**
* 实时磁盘监控
* @param request
* @param response
* @return
*/
@GetMapping("/queryDiskInfo")
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){
Result<List<Map<String,Object>>> res = new Result<>();
try {
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
log.info("查询磁盘信息:"+fs.length+"个");
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getTotalSpace()==0) {
continue;
}
Map<String,Object> map = new HashMap<>();
map.put("name", fsv.getSystemDisplayName(fs[i]));
map.put("max", fs[i].getTotalSpace());
map.put("rest", fs[i].getFreeSpace());
map.put("restPPT", fs[i].getFreeSpace()*100/fs[i].getTotalSpace());
list.add(map);
log.info(map.toString());
}
res.setResult(list);
res.success("查询成功");
} catch (Exception e) {
res.error500("查询失败"+e.getMessage());
}
return res;
}
@Override
public void register(Registry registry) {
Id basicId = registry.createId("instance.file.system");
File[] roots = File.listRoots();
// For each filesystem root;
//TODO dynamic File.listRoots() and for each;
for (final File root : roots) {
Id id = basicId.withTag("root", root.getAbsolutePath()).withTag(
LookoutConstants.LOW_PRIORITY_TAG);
MixinMetric mixin = registry.mixinMetric(id);
mixin.gauge("total.space", new Gauge<Long>() {
@Override
public Long value() {
return root.getTotalSpace();
}
});
mixin.gauge("free.space", new Gauge<Long>() {
@Override
public Long value() {
return root.getFreeSpace();
}
});
mixin.gauge("usabe.space", new Gauge<Long>() {
@Override
public Long value() {
return root.getUsableSpace();
}
});
}
}
private static boolean absolutePathStart(String path) {
File[] files = File.listRoots();
for (File file : files) {
if (path.startsWith(file.getPath())) {
return true;
}
}
return false;
}
protected static String fileToUri(String uriString) {
if (uriString.startsWith(PATH_SEPARATOR)) { // handles Linux absolute paths and UNC pathnames on Windows
return "file://" + uriString; //$NON-NLS-1$
}
String lowerCaseUri = uriString.toLowerCase();
for (File root: File.listRoots()) { // handles drive letters on Windows
String rootString = BACKSLASH_PATTERN.matcher(root.toString()).replaceFirst(PATH_SEPARATOR).toLowerCase();
if (lowerCaseUri.startsWith(rootString)) {
return "file:/" + uriString; //$NON-NLS-1$
}
}
return uriString;
}
/**
* @功能:获取磁盘信息
* @param request
* @param response
* @return
*/
@GetMapping("/queryDiskInfo")
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){
Result<List<Map<String,Object>>> res = new Result<>();
try {
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
log.info("查询磁盘信息:"+fs.length+"个");
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getTotalSpace()==0) {
continue;
}
Map<String,Object> map = new HashMap<>();
map.put("name", fsv.getSystemDisplayName(fs[i]));
map.put("max", fs[i].getTotalSpace());
map.put("rest", fs[i].getFreeSpace());
map.put("restPPT", (fs[i].getTotalSpace()-fs[i].getFreeSpace())*100/fs[i].getTotalSpace());
list.add(map);
log.info(map.toString());
}
res.setResult(list);
res.success("查询成功");
} catch (Exception e) {
res.error500("查询失败"+e.getMessage());
}
return res;
}
private void recordStats() {
long total = 0;
long free = 0;
File[] roots = File.listRoots();
for (File root : roots) {
total += root.getTotalSpace();
free += root.getFreeSpace();
}
long maxMem = Runtime.getRuntime().maxMemory();
long usedMem = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
// Stuff accessing sponge needs to be run on the server main thread
WebAPI.runOnMain(() -> {
averageTps.add(new ServerStat<>(Sponge.getServer().getTicksPerSecond()));
onlinePlayers.add(new ServerStat<>(Sponge.getServer().getOnlinePlayers().size()));
});
cpuLoad.add(new ServerStat<>(systemMXBean.getProcessCpuLoad()));
memoryLoad.add(new ServerStat<>(usedMem / (double)maxMem));
diskUsage.add(new ServerStat<>((total - free) / (double)total));
while (averageTps.size() > MAX_STATS_ENTRIES)
averageTps.poll();
while (onlinePlayers.size() > MAX_STATS_ENTRIES)
onlinePlayers.poll();
while (cpuLoad.size() > MAX_STATS_ENTRIES)
cpuLoad.poll();
while (memoryLoad.size() > MAX_STATS_ENTRIES)
memoryLoad.poll();
while (diskUsage.size() > MAX_STATS_ENTRIES)
diskUsage.poll();
}
/**
* @功能:获取磁盘信息
* @param request
* @param response
* @return
*/
@GetMapping("/queryDiskInfo")
public Result<List<Map<String,Object>>> queryDiskInfo(HttpServletRequest request, HttpServletResponse response){
Result<List<Map<String,Object>>> res = new Result<>();
try {
// 当前文件系统类
FileSystemView fsv = FileSystemView.getFileSystemView();
// 列出所有windows 磁盘
File[] fs = File.listRoots();
log.info("查询磁盘信息:"+fs.length+"个");
List<Map<String,Object>> list = new ArrayList<>();
for (int i = 0; i < fs.length; i++) {
if(fs[i].getTotalSpace()==0) {
continue;
}
Map<String,Object> map = new HashMap<>();
map.put("name", fsv.getSystemDisplayName(fs[i]));
map.put("max", fs[i].getTotalSpace());
map.put("rest", fs[i].getFreeSpace());
map.put("restPPT", (fs[i].getTotalSpace()-fs[i].getFreeSpace())*100/fs[i].getTotalSpace());
list.add(map);
log.info(map.toString());
}
res.setResult(list);
res.success("查询成功");
} catch (Exception e) {
res.error500("查询失败"+e.getMessage());
}
return res;
}
DisksInformation() {
disks = new ArrayList<>();
File[] roots = File.listRoots();
for (File root : roots) {
disks.add(
new Disk(root.getAbsolutePath(),
root.getTotalSpace(),
root.getFreeSpace())
);
}
}
/**
* Returns all local FileSystems.
*
* This method detects all local file system roots, and returns one or more <code>FileSystems</code> representing each of these roots.
*
* @return all local FileSystems.
*
* @throws XenonException
* If the creation of the FileSystem failed.
*/
public static FileSystem[] getLocalFileSystems() throws XenonException {
File[] roots = File.listRoots();
FileSystem[] result = new FileSystem[roots.length];
for (int i = 0; i < result.length; i++) {
result[i] = FileSystem.create("file", getLocalRoot(roots[i].getPath()));
}
return result;
}