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

The following are Jave code examples for showing how to use listRoots() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Open-DM   File: FileSystemProfile.java   View Source Code Vote up 6 votes
private FileSystemProfile() {
    super(ProfileManager.LOCAL_FILESYSTEM_PROFILE_ID, DEFAULT_FILESYSTEM_PROFILE_NAME);
    File[] roots = File.listRoots();

    if (roots != null && roots.length == 1) {
        // One root - probably a Unix filesystem. Set this as the ROOT_PATH
        ROOT_PATH = roots[0].getPath();
    } else {
        File current = new File(System.getProperty("user.dir"));
        File root = current.getParentFile();
        while (root.getParentFile() != null) {
            root = root.getParentFile();
        }
        ROOT_PATH = root.getPath();
    }
    displayedPath = ConfigurationHelper.getStringProperty(LOCAL_FILESYSTEM_PATH,
                                                          System.getProperty("user.home"));

}
 
Example 2
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   View Source Code Vote up 6 votes
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 3
Project: UDE   File: ClassTreeView.java   View Source Code Vote up 6 votes
@Override
public void CreateTreeView(TreeView<String> treeview){
    File[] sysroots = File.listRoots();
    TreeItem<String> ThisPc = new TreeItem<>("This PC", new ImageView(new Image(ClassLoader.getSystemResourceAsStream("img/pc.png"))));
    TreeItem<String>[] drives = new TreeItem[sysroots.length];
    for(int i=0; i<sysroots.length;i++){
        drives[i] = new TreeItem<>(sysroots[i].getAbsolutePath(), new ImageView(new Image(ClassLoader.getSystemResourceAsStream("img/thumb_Hard_Drive.png"))));
        try{
            drives[i].getChildren().addAll(TreeCreate(sysroots[i]));
        }catch(NullPointerException x){System.out.println("Exeption x detected: "+x.fillInStackTrace()+drives[i].toString());}
        finally {
            ThisPc.getChildren().add(drives[i]);
        }
    }
    treeview.setRoot(ThisPc);
}
 
Example 4
Project: incubator-netbeans   File: FileNameTest.java   View Source Code Vote up 6 votes
public void testListRoots() {
    for (File f : File.listRoots()) {
        String n = f.getPath();
        if (n.length() <= 1) {
            continue;
        }
        
        String withoutN;
        if (n.endsWith(File.separator)) {
            withoutN = n.substring(0, n.length() - 1);
        } else {
            continue;
        }
        FileNaming fWith = NamingFactory.fromFile(f);
        FileNaming fWithout = NamingFactory.fromFile(new File(withoutN));
        
        assertEquals("Roots should be the same", fWith, fWithout);
        if (Utilities.isWindows()) {
            FileNaming fUpper = NamingFactory.fromFile(new File(f.getPath().toUpperCase(Locale.ENGLISH)));
            FileNaming fLower = NamingFactory.fromFile(new File(f.getPath().toLowerCase(Locale.ENGLISH)));
            assertEquals("Lower and Upper case roots are equal on Windows", fUpper, fLower);
        }
    }
}
 
Example 5
Project: openjdk-jdk10   File: ShellFolderManager.java   View Source Code Vote up 6 votes
/**
 * @param key a {@code String}
 *  "fileChooserDefaultFolder":
 *    Returns a {@code File} - the default shellfolder for a new filechooser
 *  "roots":
 *    Returns a {@code File[]} - containing the root(s) of the displayable hierarchy
 *  "fileChooserComboBoxFolders":
 *    Returns a {@code File[]} - an array of shellfolders representing the list to
 *    show by default in the file chooser's combobox
 *   "fileChooserShortcutPanelFolders":
 *    Returns a {@code File[]} - 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} - 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
Project: parabuild-ci   File: MyUtility.java   View Source Code Vote up 6 votes
private static void constructRoots() {
    if (osName.startsWith("windows")) {
        Vector rootsVector = new Vector();
    
        // Create the A: drive whether it is mounted or not
        FileSystemRoot floppy = new FileSystemRoot("A" + ":" + "\\");
        rootsVector.addElement(floppy);

        // Run through all possible mount points and check
        // for their existance.
        for (char c = 'C'; c <= 'Z'; c++) {
            char device[] = {c, ':', '\\'};
            String deviceName = new String(device);
            File deviceFile = new FileSystemRoot(deviceName);
            if (deviceFile != null && deviceFile.exists()) {
                rootsVector.addElement(deviceFile);
            }
        }
        roots = new File[rootsVector.size()];
        rootsVector.copyInto(roots);
    } else {
        roots = File.listRoots();
    }
}
 
Example 7
Project: q-mail   File: StorageManager.java   View Source Code Vote up 5 votes
/**
 * @param file
 *            Canonical file to match. Never <code>null</code>.
 * @return Whether the specified file matches a filesystem root.
 * @throws IOException
 */
public static boolean isMountPoint(final File file) {
    for (final File root : File.listRoots()) {
        if (root.equals(file)) {
            return true;
        }
    }
    return false;
}
 
Example 8
Project: awe-awesomesky   File: SystemMonitorUtil.java   View Source Code Vote up 5 votes
/**
 * 获取系统各盘符大小
 */
public Map<String, Double> getSysSize() {
	File[] files = File.listRoots();
	Map<String, Double> map = null;
	for(int i = 0; i < files.length; i++) {
		 map = new HashMap<String, Double>();
		 long total = (long) files[i].getTotalSpace();  
            long free = (long) files[i].getFreeSpace();
            Double compare = (Double) (1 - free * 1.0 / total) * 100;
            map.put(files[i].getName(), compare);
	}
	return map;
}
 
Example 9
Project: incubator-netbeans   File: CreateFileOnWindowsTest.java   View Source Code Vote up 5 votes
public static Test suite() {
    NbTestSuite ts = new NbTestSuite();
    if (Utilities.isWindows()) {
        for (File root : File.listRoots()) {
            ts.addTest(new CreateFileOnWindowsTest(root));
        }
    }
    return ts;
}
 
Example 10
Project: SystemMonitor   File: DiskService.java   View Source Code Vote up 5 votes
public DiskService() {
    File[] diskRoots = File.listRoots();
    disks = new ArrayList<>();
    for(File file: diskRoots) {
        disks.add(new Disk(file));
    }
}
 
Example 11
Project: incubator-netbeans   File: VersioningSupportTest.java   View Source Code Vote up 5 votes
public void testFlat() {
    File f = File.listRoots()[0];
    VCSFileProxy proxy = VCSFileProxy.createFileProxy(f);
    assertFalse(APIAccessor.IMPL.isFlat(proxy));
    proxy = Utils.createFlatFileProxy(FileUtil.toFileObject(f));
    assertTrue(APIAccessor.IMPL.isFlat(proxy));
}
 
Example 12
Project: everywhere   File: FileUtil.java   View Source Code Vote up 5 votes
public static List<String> getDriver() {
    List<String> driverList = new ArrayList<>();
    File[] fs = File.listRoots();

    for (int i = 0; i < fs.length; i++) {
        driverList.add(fs[i].getAbsolutePath());
    }
    return driverList;
}
 
Example 13
Project: incubator-netbeans   File: I18nOptions.java   View Source Code Vote up 5 votes
private static FileSystem[] getFileSystems() {
    List<FileSystem> retval = new ArrayList<FileSystem>();
    for (File file : File.listRoots()) {
        FileObject fo = FileUtil.toFileObject(file);
        if (fo != null) {
            try {
                retval.add(fo.getFileSystem());
            } catch (FileStateInvalidException ex) {
                    LOG.log(Level.INFO, null, ex);
            }
        }
    }        
    return retval.toArray(new FileSystem[retval.size()]);
}
 
Example 14
Project: proxyee-down   File: HttpDownController.java   View Source Code Vote up 4 votes
@RequestMapping("/getChildDirList")
public ResultInfo getChildDirList(@RequestParam String model,
    @RequestBody(required = false) DirInfo body) {
  ResultInfo resultInfo = new ResultInfo();
  List<DirInfo> data = new LinkedList<>();
  resultInfo.setData(data);
  File[] files;
  if (body == null || StringUtils.isEmpty(body.getPath())) {
    files = File.listRoots();
  } else {
    File file = new File(body.getPath());
    if (file.exists() && file.isDirectory()) {
      files = file.listFiles();
    } else {
      resultInfo.setStatus(ResultStatus.BAD.getCode()).setMsg("路径不存在");
      return resultInfo;
    }
  }
  if (files != null && files.length > 0) {
    boolean isFileList = "file".equals(model);
    for (File tempFile : files) {
      if (tempFile.isFile()) {
        if (isFileList) {
          data.add(new DirInfo(
              StringUtils.isEmpty(tempFile.getName()) ? tempFile.getAbsolutePath()
                  : tempFile.getName(), tempFile.getAbsolutePath(), true));
        }
      } else if (tempFile.isDirectory() && (tempFile.getParent() == null || !tempFile
          .isHidden())) {
        DirInfo dirInfo = new DirInfo(
            StringUtils.isEmpty(tempFile.getName()) ? tempFile.getAbsolutePath()
                : tempFile.getName(), tempFile.getAbsolutePath(),
            tempFile.listFiles() == null ? true : Arrays.stream(tempFile.listFiles())
                .noneMatch(file ->
                    file != null && (file.isDirectory() || isFileList) && !file.isHidden()
                ));
        data.add(dirInfo);
      }
    }
  }
  return resultInfo;
}
 
Example 15
Project: monarch   File: DirPathConverter.java   View Source Code Vote up 4 votes
@Override
public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType,
    String existingData, String optionContext, MethodTarget target) {
  // prefix is needed while comparing Completion Candidates as potential matches
  String prefixToUse = "";
  boolean prependAbsolute = true;
  File parentDir = null; // directory to be searched for file(s)

  if (existingData != null) {
    // System.out.println("FilePathConverter.getAllPossibleValues() : optionContext ::
    // "+optionContext+", existingData : "+existingData);
    String[] completionValues = new String[0];

    if (ConverterHint.DIR_PATHSTRING.equals(optionContext)) {
      // if existingData is empty, start from root
      if (existingData != null && existingData.trim().isEmpty()) {
        File[] listRoots = File.listRoots();
        completionValues = new String[listRoots.length];
        for (int i = 0; i < listRoots.length; i++) {
          if (listRoots[i].isDirectory()) {
            completionValues[i] = listRoots[i].getPath();
          }
        }
        prefixToUse = File.separator;
      } else {
        // Create a file from existing data
        File file = new File(existingData);
        if (file.isDirectory()) {
          // For a directory, list files/sub-dirs in the directory
          parentDir = file;
          completionValues = parentDir.list(dirFilter);
        } else if (!file.exists()) {
          parentDir = file.getParentFile();
          if (parentDir == null) {
            try {
              parentDir = file.getCanonicalFile().getParentFile();
            } catch (IOException e) {
              parentDir = null;
            }
          }
          if (parentDir != null) {
            completionValues = parentDir.list(new DirNameFilterImpl(parentDir, file.getName()));
          }
        }
        // whether the file path is absolute
        prependAbsolute = file.isAbsolute();
      }
    }

    if (completionValues.length > 0) {
      // use directory path as prefix for completion of names of the contained files
      if (parentDir != null) {
        if (existingData.startsWith(".")) { // handle . & ..
          prefixToUse = parentDir.getPath();
        } else if (prependAbsolute) {
          prefixToUse = parentDir.getAbsolutePath();
        }
      }
      // add File.separator in the end
      if (!prefixToUse.endsWith(File.separator)
          && (prependAbsolute || existingData.startsWith("."))) {
        prefixToUse += File.separator;
      }
      for (int i = 0; i < completionValues.length; i++) {
        completions.add(new Completion(prefixToUse + completionValues[i]));
      }
    }
  }

  return !completions.isEmpty();
}
 
Example 16
Project: incubator-netbeans   File: TreeModelExample1.java   View Source Code Vote up 4 votes
public Object[] getChildren (Object parent, int from, int to) {
    if (parent == ROOT)
        return File.listRoots ();
    return ((File) parent).listFiles ();
}
 
Example 17
Project: monarch   File: FilePathConverter.java   View Source Code Vote up 4 votes
@Override
public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType,
    String existingData, String optionContext, MethodTarget target) {
  // prefix is needed while comparing Completion Candidates as potential matches
  String prefixToUse = "";
  boolean prependAbsolute = true;
  File parentDir = null; // directory to be searched for file(s)

  if (existingData != null) {
    // System.out.println("FilePathConverter.getAllPossibleValues() : optionContext ::
    // "+optionContext+", existingData : "+existingData);
    String[] completionValues = new String[0];

    if (ConverterHint.FILE.equals(optionContext)) {
      // if existingData is empty, start from root
      if (existingData != null && existingData.trim().isEmpty()) {
        File[] listRoots = File.listRoots();
        completionValues = new String[listRoots.length];
        for (int i = 0; i < listRoots.length; i++) {
          completionValues[i] = listRoots[i].getPath();
        }
        prefixToUse = File.separator;
      } else {
        // Create a file from existing data
        File file = new File(existingData);
        if (file.isDirectory()) {
          // For a directory, list files/sub-dirsin the directory
          parentDir = file;
          completionValues = parentDir.list();
        } else if (!file.exists()) {
          parentDir = file.getParentFile();
          if (parentDir == null) {
            try {
              parentDir = file.getCanonicalFile().getParentFile();
            } catch (IOException e) {
              parentDir = null;
            }
          }
          if (parentDir != null) {
            completionValues = parentDir.list(new FileNameFilterImpl(parentDir, file.getName()));
          }
        }
        // whether the file path is absolute
        prependAbsolute = file.isAbsolute();
      }
    }

    if (completionValues.length > 0) {
      // use directory path as prefix for completion of names of the contained files
      if (parentDir != null) {
        if (existingData.startsWith(".")) { // handle . & ..
          prefixToUse = parentDir.getPath();
        } else if (prependAbsolute) {
          prefixToUse = parentDir.getAbsolutePath();
        }
      }
      // add File.separator in the end
      if (!prefixToUse.endsWith(File.separator)
          && (prependAbsolute || existingData.startsWith("."))) {
        prefixToUse += File.separator;
      }
      for (int i = 0; i < completionValues.length; i++) {
        completions.add(new Completion(prefixToUse + completionValues[i]));
      }
    }
  }

  return !completions.isEmpty();
}
 
Example 18
Project: incubator-netbeans   File: TreeModelExample4.java   View Source Code Vote up 4 votes
public Object[] getChildren (Object parent, int from, int to) {
    if (parent == ROOT)
        return File.listRoots ();
    return ((File) parent).listFiles ();
}
 
Example 19
Project: guava-mock   File: FilesTest.java   View Source Code Vote up 4 votes
/**
 * Returns a root path for the file system.
 */
private static File root() {
  return File.listRoots()[0];
}
 
Example 20
Project: googles-monorepo-demo   File: FilesTest.java   View Source Code Vote up 4 votes
/**
 * Returns a root path for the file system.
 */
private static File root() {
  return File.listRoots()[0];
}