Example usage for java.io File listRoots

List of usage examples for java.io File listRoots

Introduction

In this page you can find the example usage for java.io File listRoots.

Prototype

public static File[] listRoots() 

Source Link

Document

List the available filesystem roots.

Usage

From source file:FileTree3.java

public FileTree3() {
    super("Directories Tree [Tool Tips]");
    setSize(400, 300);/* w  w w .j  av a  2s  . c  o  m*/

    DefaultMutableTreeNode top = new DefaultMutableTreeNode(new IconData(ICON_COMPUTER, null, "Computer"));

    DefaultMutableTreeNode node;
    File[] roots = File.listRoots();
    for (int k = 0; k < roots.length; k++) {
        node = new DefaultMutableTreeNode(new IconData(ICON_DISK, null, new FileNode(roots[k])));
        top.add(node);
        node.add(new DefaultMutableTreeNode(new Boolean(true)));
    }

    m_model = new DefaultTreeModel(top);
    // NEW
    m_tree = new JTree(m_model) {
        public String getToolTipText(MouseEvent ev) {
            if (ev == null)
                return null;
            TreePath path = m_tree.getPathForLocation(ev.getX(), ev.getY());
            if (path != null) {
                FileNode fnode = getFileNode(getTreeNode(path));
                if (fnode == null)
                    return null;
                File f = fnode.getFile();
                return (f == null ? null : f.getPath());
            }
            return null;
        }
    };
    ToolTipManager.sharedInstance().registerComponent(m_tree);

    m_tree.putClientProperty("JTree.lineStyle", "Angled");

    TreeCellRenderer renderer = new IconCellRenderer();
    m_tree.setCellRenderer(renderer);

    m_tree.addTreeExpansionListener(new DirExpansionListener());

    m_tree.addTreeSelectionListener(new DirSelectionListener());

    m_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    m_tree.setShowsRootHandles(true);
    m_tree.setEditable(false);

    JScrollPane s = new JScrollPane();
    s.getViewport().add(m_tree);
    getContentPane().add(s, BorderLayout.CENTER);

    m_display = new JTextField();
    m_display.setEditable(false);
    getContentPane().add(m_display, BorderLayout.NORTH);

    m_popup = new JPopupMenu();
    m_action = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            if (m_clickedPath == null)
                return;
            if (m_tree.isExpanded(m_clickedPath))
                m_tree.collapsePath(m_clickedPath);
            else
                m_tree.expandPath(m_clickedPath);
        }
    };
    m_popup.add(m_action);
    m_popup.addSeparator();

    Action a1 = new AbstractAction("Delete") {
        public void actionPerformed(ActionEvent e) {
            m_tree.repaint();
            JOptionPane.showMessageDialog(FileTree3.this, "Delete option is not implemented", "Info",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    };
    m_popup.add(a1);

    Action a2 = new AbstractAction("Rename") {
        public void actionPerformed(ActionEvent e) {
            m_tree.repaint();
            JOptionPane.showMessageDialog(FileTree3.this, "Rename option is not implemented", "Info",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    };
    m_popup.add(a2);
    m_tree.add(m_popup);
    m_tree.addMouseListener(new PopupTrigger());

    WindowListener wndCloser = new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    };
    addWindowListener(wndCloser);

    setVisible(true);
}

From source file:org.opendatakit.briefcase.util.FindDirectoryStructure.java

/**
 * Searches mounted drives for /odk/instances and returns a list of
 * positive results. Works for Windows, Mac, and Linux operating
 * systems.//from   w w  w .  j  ava2 s.  c  o m
 *
 * @return a {@link List} of {@link File}  containing matches of currently mounted file systems
 *         which contain the directoryStructureToSearchFor
 */
public static List<File> searchMountedDrives() {
    String os = System.getProperty(PROPERTY_OS);
    log.info("OS reported as: " + os);
    if (os.contains(OS_WINDOWS)) {
        File[] drives = File.listRoots();
        return search(drives, true);
    } else if (os.contains(OS_MAC)) {
        File[] mounts = { new File("/Volumes"), new File("/media"), new File("/mnt") };
        return search(mounts, false);
    } else // Assume Unix
    {
        String username = System.getProperty(USER_NAME);
        List<File> mountslist = new ArrayList<File>();
        mountslist.add(new File("/mnt"));
        mountslist.add(new File("/media"));

        File f = new File("/media", username);
        if (f.exists() && f.isDirectory()) {
            mountslist.add(f);
        }

        f = new File("/run/media", username);
        if (f.exists() && f.isDirectory()) {
            mountslist.add(f);
        }
        return search(mountslist.toArray(new File[mountslist.size()]), false);
    }
}

From source file:org.apache.geode.management.internal.cli.converters.FilePathStringConverter.java

public List<String> getRoots() {
    File[] roots = File.listRoots();
    return Arrays.stream(roots).map(File::getAbsolutePath).collect(Collectors.toList());
}

From source file:musicmetadatak1009705.FolderTreeView.java

public VBox treeStack() throws IOException {
    VBox vbox = new VBox();
    File[] drives = File.listRoots();
    ArrayList<File> fileListing;
    /*for (File dir : drives) {
     System.out.println(dir.toString());
     fileListing = restrictingList(dir);
     }*//*from w  w w  .j  a  v  a2s  .  com*/
    fileListing = restrictingList(new File("D:\\"));

    ArrayList<TreeItem> treeItems = new ArrayList<>();
    for (File dir : drives) {
        //System.out.println(dir.toString());
        treeItems.add(createNode(dir));
    }
    TreeView<File> tree = proxyCreateNode(treeItems);
    vbox.getChildren().add(tree);

    tree.getSelectionModel().selectedItemProperty()
            .addListener((ObservableValue<? extends TreeItem<File>> observable, TreeItem<File> oldValue,
                    TreeItem<File> newValue) -> {
                System.out.println("Selected Text: " + newValue.getValue());
                TreeItem<File> selectedItem = newValue;
                System.out.println("Selected Text: " + selectedItem.getValue());
                try {
                    //FileTreeView fileTreeView = new FileTreeView();
                    System.out.println("File Tree View Event");
                    fileTreeView.GetFilesFromFolder((newValue.getValue().toString()));
                    //fileTreeView.SetFileTreeView();
                } catch (IOException ex) {
                    System.err.println("Unable to pass fileTreeView Value \nPassed Value: "
                            + selectedItem.getValue().toString() + "\r\nError Message:\r\n" + ex.toString());
                    Logger.getLogger(FolderTreeView.class.getName()).log(Level.SEVERE, null, ex);
                }
            } /* @Override
              public void changed(
              ObservableValue<? extends TreeItem<File>> observable, TreeItem<String> old_val, TreeItem<File> new_val) {
              }*/ );
    return vbox;
}

From source file:com.norconex.commons.wicket.markup.html.filesystem.FileSystemTreeProvider.java

@Override
public Iterator<? extends File> getRoots() {
    if (isWindowsRoot(root)) {
        return Arrays.asList(File.listRoots()).iterator();
    }//w  w  w.  jav a  2 s .co  m
    return Arrays.asList(root.listFiles(fileNameFilter)).iterator();
}

From source file:org.apache.sling.ide.impl.vlt.serialization.VltSerializationManagerTest.java

private File findFilesystemRoot() {
    File[] roots = File.listRoots();
    Assume.assumeTrue("No filesystem roots found", roots != null && roots.length > 0);
    return roots[0];
}

From source file:Testing.TestMain.java

public static String[] getListOfMP3Files() {
    //List<String> listOfFiles = new ArrayList<>();
    // C:\ D:\//ww  w . j  av a  2  s .  c  o  m
    File[] drives = File.listRoots();
    // none of this works, Why does it fail??? it just crashes after one attempt, Needs to run recursivly down each folder,recursive
    for (File rootDirectory : drives) {
        File directory = new File(rootDirectory.getPath());
        System.out.println(rootDirectory.getPath());
        return directory.list(new FilenameFilter() {
            public boolean accept(File directory, String filename) {
                return filename.endsWith(".mp3");
            }
        });

    }
    return null;
}

From source file:org.gradle.api.internal.file.FileNormaliser.java

public File normalise(File file) {
    try {/* ww w. j a  va2 s  .c o m*/
        if (!file.isAbsolute()) {
            throw new IllegalArgumentException(String.format("Cannot normalize a relative file: '%s'", file));
        }

        if (isWindowsOs) {
            // on Windows, File.getCanonicalFile() doesn't resolve symlinks
            return file.getCanonicalFile();
        }

        File candidate;
        String filePath = file.getPath();
        List<String> path = null;
        if (isNormalisingRequiredForAbsolutePath(filePath)) {
            path = splitAndNormalisePath(filePath);
            String resolvedPath = CollectionUtils.join(File.separator, path);
            boolean needLeadingSeparator = File.listRoots()[0].getPath().startsWith(File.separator);
            if (needLeadingSeparator) {
                resolvedPath = File.separator + resolvedPath;
            }
            candidate = new File(resolvedPath);
        } else {
            candidate = file;
        }

        // If the file system is case sensitive, we don't have to normalise it further
        if (fileSystem.isCaseSensitive()) {
            return candidate;
        }

        // Short-circuit the slower lookup method by using the canonical file
        File canonical = candidate.getCanonicalFile();
        if (candidate.getPath().equalsIgnoreCase(canonical.getPath())) {
            return canonical;
        }

        // Canonical path is different to what we expected (eg there is a link somewhere in there). Normalise a segment at a time
        // TODO - start resolving only from where the expected and canonical paths are different
        if (path == null) {
            path = splitAndNormalisePath(filePath);
        }
        return normaliseUnixPathIgnoringCase(path);
    } catch (IOException e) {
        throw new UncheckedIOException(String.format("Could not normalize path for file '%s'.", file), e);
    }
}

From source file:net.centro.rtb.monitoringcenter.infos.OperatingSystemInfo.java

public static OperatingSystemInfo create() {
    OperatingSystemInfo operatingSystemInfo = new OperatingSystemInfo();

    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();

    operatingSystemInfo.name = operatingSystemMXBean.getName();
    operatingSystemInfo.version = operatingSystemMXBean.getVersion();

    if (SystemUtils.IS_OS_LINUX) {
        operatingSystemInfo.distributionName = resolveLinuxDistributionName();
    }/*from w w  w  . j av a  2s .c o m*/

    operatingSystemInfo.architecture = operatingSystemMXBean.getArch();
    operatingSystemInfo.numberOfLogicalProcessors = operatingSystemMXBean.getAvailableProcessors();

    if (com.sun.management.OperatingSystemMXBean.class.isAssignableFrom(operatingSystemMXBean.getClass())) {
        com.sun.management.OperatingSystemMXBean sunOsMxBean = com.sun.management.OperatingSystemMXBean.class
                .cast(operatingSystemMXBean);
        operatingSystemInfo.physicalMemorySizeInBytes = sunOsMxBean.getTotalPhysicalMemorySize();
        operatingSystemInfo.swapSpaceSizeInBytes = sunOsMxBean.getTotalSwapSpaceSize();
    }

    Map<String, Long> diskSpaceInBytesByRootPaths = new HashMap<>();
    for (File rootFile : File.listRoots()) {
        diskSpaceInBytesByRootPaths.put(rootFile.getAbsolutePath(), rootFile.getTotalSpace());
    }
    operatingSystemInfo.diskSpaceInBytesByRootPaths = diskSpaceInBytesByRootPaths;

    return operatingSystemInfo;
}

From source file:org.geoserver.web.wicket.browser.GeoServerFileChooser.java

/**
 * Constructor with optional flag to control how file system resources are exposed.
 * <p>/*from   ww  w  .j  av  a  2s .c o  m*/
 * When <tt>hideFileSyste</tt> is set to <tt>true</tt> only the data directory is exposed 
 * in the file browser. 
 * </p>
 */
public GeoServerFileChooser(String id, IModel file, boolean hideFileSystem) {
    super(id, file);

    this.file = file;
    this.hideFileSystem = hideFileSystem;

    // build the roots
    ArrayList<File> roots = new ArrayList<File>();
    if (!hideFileSystem) {
        roots.addAll(Arrays.asList(File.listRoots()));
    }
    Collections.sort(roots);

    // TODO: find a better way to deal with the data dir
    File dataDirectory = GeoserverDataDirectory.getGeoserverDataDirectory();
    roots.add(0, dataDirectory);

    // add the home directory as well if it was possible to determine it at all
    if (!hideFileSystem && USER_HOME != null) {
        roots.add(1, USER_HOME);
    }

    // find under which root the selection should be placed
    File selection = (File) file.getObject();

    // first check if the file is a relative reference into the data dir
    if (selection != null) {
        File relativeToDataDir = GeoserverDataDirectory.findDataFile(selection.getPath());
        if (relativeToDataDir != null) {
            selection = relativeToDataDir;
        }
    }

    // select the proper root
    File selectionRoot = null;
    if (selection != null && selection.exists()) {
        for (File root : roots) {
            if (isSubfile(root, selection.getAbsoluteFile())) {
                selectionRoot = root;
                break;
            }
        }

        // if the file is not part of the known search paths, give up 
        // and switch back to the data directory
        if (selectionRoot == null) {
            selectionRoot = dataDirectory;
            file = new Model(selectionRoot);
        } else {
            if (!selection.isDirectory()) {
                file = new Model(selection.getParentFile());
            } else {
                file = new Model(selection);
            }
        }
    } else {
        selectionRoot = dataDirectory;
        file = new Model(selectionRoot);
    }
    this.file = file;
    setDefaultModel(file);

    // the root chooser
    final DropDownChoice choice = new DropDownChoice("roots", new Model(selectionRoot), new Model(roots),
            new FileRootsRenderer());
    choice.add(new AjaxFormComponentUpdatingBehavior("onchange") {

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            File selection = (File) choice.getModelObject();
            breadcrumbs.setRootFile(selection);
            updateFileBrowser(selection, target);
        }

    });
    choice.setOutputMarkupId(true);
    add(choice);

    // the breadcrumbs
    breadcrumbs = new FileBreadcrumbs("breadcrumbs", new Model(selectionRoot), file) {

        @Override
        protected void pathItemClicked(File file, AjaxRequestTarget target) {
            updateFileBrowser(file, target);
        }

    };
    breadcrumbs.setOutputMarkupId(true);
    add(breadcrumbs);

    // the file tables
    fileTable = new FileDataView("fileTable", new FileProvider(file)) {

        @Override
        protected void linkNameClicked(File file, AjaxRequestTarget target) {
            updateFileBrowser(file, target);
        }

    };
    fileTable.setOutputMarkupId(true);
    add(fileTable);
}