java.io.File#listRoots ( )源码实例Demo

下面列出了java.io.File#listRoots ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jdk8u60   文件: ShellFolderManager.java
/**
 * @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;
}
 
源代码2 项目: tikione-steam-cleaner   文件: Config.java
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;
}
 
源代码3 项目: SWET   文件: OSUtils.java
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());
}
 
源代码5 项目: The-5zig-Mod   文件: FileSelector.java
@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);
}
 
源代码6 项目: The-5zig-Mod   文件: FileSelector.java
@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);
}
 
源代码7 项目: gsn   文件: DiskSpaceWrapper.java
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);
    }
}
 
源代码8 项目: ant-ivy   文件: IvyCacheFilesetTest.java
@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);
}
 
源代码9 项目: jdk8u_jdk   文件: ShellFolderManager.java
/**
 * @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;
}
 
源代码10 项目: netbeans   文件: BaseFileObjectTestHid.java
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);
}
 
源代码11 项目: dragonwell8_jdk   文件: ShellFolderManager.java
/**
 * @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;
}
 
源代码12 项目: jeecg-boot-with-activiti   文件: MockController.java
/**
   * 实时磁盘监控
 * @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();
            }
        });
    }
}
 
源代码14 项目: Sentinel   文件: ConfigUtil.java
private static boolean absolutePathStart(String path) {
    File[] files = File.listRoots();
    for (File file : files) {
        if (path.startsWith(file.getPath())) {
            return true;
        }
    }
    return false;
}
 
源代码15 项目: CloverETL-Engine   文件: CloverURI.java
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;
}
 
源代码16 项目: jeecg-boot   文件: ActuatorRedisController.java
/**
 * @功能:获取磁盘信息
 * @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;
}
 
源代码17 项目: Web-API   文件: ServerService.java
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();
}
 
源代码18 项目: jeecg-cloud   文件: ActuatorRedisController.java
/**
 * @功能:获取磁盘信息
 * @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;
}
 
源代码19 项目: FlyingAgent   文件: DisksInformation.java
DisksInformation() {
    disks = new ArrayList<>();

    File[] roots = File.listRoots();

    for (File root : roots) {
        disks.add(
                new Disk(root.getAbsolutePath(),
                        root.getTotalSpace(),
                        root.getFreeSpace())
        );
    }

}
 
源代码20 项目: xenon   文件: LocalFileSystemUtils.java
/**
 * 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;
}