Java Code Examples for java.io.File#listRoots()

The following examples show how to use java.io.File#listRoots() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ShellFolderManager.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example 2
Source File: Config.java    From tikione-steam-cleaner with MIT License 6 votes vote down vote up
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;
}
 
Example 3
Source File: OSUtils.java    From SWET with MIT License 6 votes vote down vote up
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;
}
 
Example 4
Source File: SelectSettlersFolderDialog.java    From settlers-remake with MIT License 6 votes vote down vote up
/**
 * 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());
}
 
Example 5
Source File: ShellFolderManager.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example 6
Source File: FileSelector.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
@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);
}
 
Example 7
Source File: FileSelector.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
@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);
}
 
Example 8
Source File: DiskSpaceWrapper.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example 9
Source File: IvyCacheFilesetTest.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 10
Source File: ShellFolderManager.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example 11
Source File: BaseFileObjectTestHid.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 12
Source File: DisksInformation.java    From FlyingAgent with Apache License 2.0 5 votes vote down vote up
DisksInformation() {
    disks = new ArrayList<>();

    File[] roots = File.listRoots();

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

}
 
Example 13
Source File: ActuatorRedisController.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * @功能:获取磁盘信息
 * @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;
}
 
Example 14
Source File: ServerService.java    From Web-API with MIT License 5 votes vote down vote up
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();
}
 
Example 15
Source File: ActuatorRedisController.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * @功能:获取磁盘信息
 * @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;
}
 
Example 16
Source File: CloverURI.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
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;
}
 
Example 17
Source File: ConfigUtil.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static boolean absolutePathStart(String path) {
    File[] files = File.listRoots();
    for (File file : files) {
        if (path.startsWith(file.getPath())) {
            return true;
        }
    }
    return false;
}
 
Example 18
Source File: FileSystemSpaceMetricsImporter.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
@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();
            }
        });
    }
}
 
Example 19
Source File: MockController.java    From jeecg-boot-with-activiti with MIT License 5 votes vote down vote up
/**
   * 实时磁盘监控
 * @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;
}
 
Example 20
Source File: LocalFileSystemUtils.java    From xenon with Apache License 2.0 3 votes vote down vote up
/**
 * 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;
}