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:org.jini.commands.info.ListRoots.java

private void printRoots() {
    TablePrinter tableF = new TablePrinter("Name", "TotalSpace (GB)", "FreeSpace (GB)");
    DecimalFormat df = new DecimalFormat("#######.##");

    File[] roots = File.listRoots();
    for (int i = 0; i < roots.length; i++) {
        long freeSpaceBytes = roots[i].getFreeSpace();
        long totalSpaceBytes = roots[i].getTotalSpace();
        tableF.addRow(roots[i].toString(), df.format(fileSize.convertBytesToGigabytes(freeSpaceBytes)),
                df.format(fileSize.convertBytesToGigabytes(totalSpaceBytes)));
    }/*ww  w  .ja va 2  s.co  m*/

    tableF.print();
}

From source file:org.geogig.geoserver.web.repository.DirectoryChooser.java

public DirectoryChooser(final String contentId, IModel<File> initialDirectory,
        final boolean makeRepositoriesSelectable) {
    super(contentId, initialDirectory);
    getSession().bind();// so we can store the last visited directory as a session object
    this.makeRepositoriesSelectable = makeRepositoriesSelectable;

    if (initialDirectory.getObject() == null) {
        File lastUsed = getSession().getMetaData(LAST_VISITED_DIRECTORY);
        initialDirectory.setObject(lastUsed);
    }//from   w  w  w.  ja  v a2  s.co m

    // build the roots
    ArrayList<File> roots = Lists.newArrayList(File.listRoots());
    Collections.sort(roots);

    // TODO: find a better way to deal with the data dir
    GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class);
    File dataDirectory = loader.getBaseDirectory();

    roots.add(0, dataDirectory);

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

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

    // first check if the file is a relative reference into the data dir
    if (selection != null) {
        File relativeToDataDir = loader.url(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;
            initialDirectory = new Model<>(selectionRoot);
        } else {
            if (!selection.isDirectory()) {
                initialDirectory = new Model<>(selection.getParentFile());
            } else {
                initialDirectory = new Model<>(selection);
            }
        }
    } else {
        selectionRoot = dataDirectory;
        initialDirectory = new Model<>(selectionRoot);
    }
    this.directory = initialDirectory;
    setDefaultModel(initialDirectory);

    // the root chooser
    final DropDownChoice<File> choice = new DropDownChoice<>("roots", new Model<>(selectionRoot),
            new Model<ArrayList<File>>(roots), new FileRootsRenderer());
    choice.add(new AjaxFormComponentUpdatingBehavior("change") {
        private static final long serialVersionUID = -1113141016446727615L;

        @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), initialDirectory) {
        private static final long serialVersionUID = 3637173832581301482L;

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

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

    // the file tables
    directoryListingTable = new DirectoryDataView("fileTable", new FileProvider(initialDirectory),
            this.makeRepositoriesSelectable) {

        private static final long serialVersionUID = -1559299096797421815L;

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

    };
    directoryListingTable.setOutputMarkupId(true);
    directoryListingTable.setFileFilter(fileFilter);
    add(directoryListingTable);

    accepdDirectoryLink = new AjaxLink<File>("ok", this.directory) {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {
            // must of been set by #directoryClicked()
            File dir = getModelObject();
            getSession().setMetaData(LAST_VISITED_DIRECTORY, dir);
            directorySelected(dir, target);
        }
    };
    add(accepdDirectoryLink);
    accepdDirectoryLink.setVisible(!this.makeRepositoriesSelectable);
}

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

private File normaliseUnixPathIgnoringCase(List<String> path) throws IOException {
    File current = File.listRoots()[0];
    for (int pos = 0; pos < path.size(); pos++) {
        File child = findChildIgnoringCase(current, path.get(pos));
        if (child == null) {
            current = new File(current, CollectionUtils.join(File.separator, path.subList(pos, path.size())));
            break;
        }/* www  .j av  a 2 s  .  com*/
        current = child;
    }
    return current;
}

From source file:org.zilverline.service.TestCollectionManagerImpl.java

public void testFile2CacheDirFromDrive() {
    try {//from w w w  .ja  v a 2s  .com
        FileSystemCollection col = new FileSystemCollection();
        File tempDirectory = new File(System.getProperty("java.io.tmpdir"), "zilverline");
        File contentDirectory = null;

        // create contentDir
        File[] drives = File.listRoots();

        for (int i = 0; i < drives.length; i++) {
            if (drives[i].getAbsolutePath().equalsIgnoreCase("A:\\")) {
                continue;
            }

            if (drives[i].getAbsolutePath().equalsIgnoreCase("B:\\")) {
                continue;
            }

            if (drives[i].canWrite()) {
                contentDirectory = drives[i];
                break;
            }
        }
        col.setContentDir(contentDirectory);

        if (!contentDirectory.exists()) {
            assertTrue("must be able to create content at: " + contentDirectory, contentDirectory.mkdirs());
        }
        col.setContentDir(contentDirectory);
        // create cacheDir
        File cacheDirectory = new File(tempDirectory, "cache");
        col.setCacheDir(cacheDirectory);
        if (!cacheDirectory.exists()) {
            assertTrue("must be able to create cache at: " + cacheDirectory, cacheDirectory.mkdirs());
        }

        // create a file in contentDir
        File tempFile = File.createTempFile("test", ".zip", contentDirectory);

        assertTrue(tempFile.isFile());
        assertTrue(tempFile.exists());

        // test file2Dir since the file is within contentDir, it should be
        // mapped to the cache
        File dir = CollectionManagerImpl.file2CacheDir(tempFile, col);

        assertTrue(dir.isDirectory());

        // clean up
        assertTrue("must be able to remove dir from: " + dir, FileUtils.removeDir(dir));
        assertTrue("must be able to remove cache from: " + cacheDirectory, FileUtils.removeDir(cacheDirectory));
        assertTrue("must be able to remove temp from: " + tempDirectory, FileUtils.removeDir(tempDirectory));
    } catch (Exception e) {
        fail("Should not happen, Exception: " + e.toString());
    }
}

From source file:org.artifactory.common.wicket.component.file.path.PathHelper.java

private static String getRootPattern() {
    StringBuilder pattern = new StringBuilder();
    pattern.append("/");
    for (File file : File.listRoots()) {
        String drive = file.getAbsolutePath().replace('\\', '/');
        pattern.append("|");
        pattern.append(drive);//from w  w  w.j a  va 2 s .  c o  m
        pattern.append("|");
        pattern.append(drive.toLowerCase());
    }
    return pattern.toString();
}

From source file:Ch12FileBrowserComposite.java

private void buildListViewer(Composite parent) {
    viewer = new ListViewer(parent);
    viewer.setLabelProvider(new LabelProvider() {
        public String getText(Object element) {
            File file = (File) element;
            String name = file.getName();
            return file.isDirectory() ? "<Dir> " + name : name;
        }/*from  w w w .  j a v a  2 s. c  o m*/
    });

    viewer.setContentProvider(new IStructuredContentProvider() {

        public Object[] getElements(Object inputElement) {
            File file = (File) inputElement;
            if (file.isDirectory()) {
                return file.listFiles();
            } else {
                return new Object[] { file.getName() };
            }
        }

        public void dispose() {
        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }
    });

    viewer.setSorter(new ViewerSorter() {

        public int category(Object element) {
            return ((File) element).isDirectory() ? 0 : 1;
        }

        public int compare(Viewer viewer, Object e1, Object e2) {
            int cat1 = category(e1);
            int cat2 = category(e2);
            if (cat1 != cat2)
                return cat1 - cat2;

            return ((File) e1).getName().compareTo(((File) e2).getName());
        }
    });

    viewer.addDoubleClickListener(new IDoubleClickListener() {

        public void doubleClick(DoubleClickEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            setCurrentDirectory((File) selection.getFirstElement());
        }
    });

    setCurrentDirectory(File.listRoots()[0]);
}

From source file:org.thingsplode.agent.monitors.providers.SystemComponentProvider.java

private List<Component> getStorage() {
    List<Component> storageComps = new ArrayList<>();
    Arrays.asList(File.listRoots()).forEach(r -> {
        Component rootFsComp = Component.create(r.getName(), Component.Type.HARDWARE, EnabledState.ENABLED);
        rootFsComp.putStatusInfo(StatusInfo.ONLINE).addCapabilities(Capability.CapabilityBuilder.newBuilder()
                .add("absolut_path", Capability.Type.READ, true, Value.Type.TEXT, r.getAbsolutePath())
                .add("free_space", Capability.Type.READ, true, Value.Type.NUMBER,
                        String.valueOf(r.getFreeSpace()))
                .add("total_space", Capability.Type.READ, true, Value.Type.NUMBER,
                        String.valueOf(r.getTotalSpace()))
                .add("can_read", Capability.Type.READ, true, Value.Type.BOOLEAN, String.valueOf(r.canRead()))
                .add("can_write", Capability.Type.READ, true, Value.Type.BOOLEAN, String.valueOf(r.canWrite()))
                .build());//w ww  .  ja v a  2s. com
        storageComps.add(rootFsComp);
    });

    return storageComps;
}

From source file:fr.msch.wissl.server.TestIndexer.java

public void test() throws Exception {
    HttpClient client = new HttpClient();

    // /indexer/status as user: 401
    GetMethod get = new GetMethod(URL + "indexer/status");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);//from  ww w  . j  a v  a  2 s.  c o m
    Assert.assertEquals(401, get.getStatusCode());

    // /indexer/status as admin: 200
    get = new GetMethod(URL + "indexer/status");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    JSONObject obj = new JSONObject(get.getResponseBodyAsString());
    // won't try to check the actual content of this object,
    // since I can't predict easily and accurately if 
    // the Indexer will be in Running or Sleeping state at a given time.
    assertTrue(obj.has("running"));
    assertTrue(obj.has("percentDone"));
    assertTrue(obj.has("secondsLeft"));
    assertTrue(obj.has("songsDone"));
    assertTrue(obj.has("songsTodo"));

    // /indexer/rescan as user: 401
    PostMethod post = new PostMethod(URL + "indexer/rescan");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /indexer/rescan as amdin
    post = new PostMethod(URL + "indexer/rescan");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    // /folders as user: 401
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    // /folders: should be empty
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("folders").length());

    // /folders/listing as user: 401
    get = new GetMethod(URL + "folders/listing");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    // /folders/listing on some file that does not exist: 404
    get = new GetMethod(URL + "folders/listing?directory=/does/not/exist");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(404, get.getStatusCode());

    File exp_home = new File(System.getProperty("user.home"));

    // /folders/listing with no arg: homedir
    get = new GetMethod(URL + "folders/listing");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    File dir = new File(obj.getString("directory"));
    assertEquals(exp_home.getAbsolutePath(), dir.getAbsolutePath());
    assertEquals(exp_home.getParentFile().getAbsolutePath(), dir.getParentFile().getAbsolutePath());
    assertTrue(obj.getJSONArray("listing").length() > 0);

    // /folders/listing with arg '$ROOT'
    get = new GetMethod(URL + "folders/listing?directory=$ROOT");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    File[] dirs = File.listRoots();
    assertEquals("", obj.getString("directory"));
    assertEquals("$ROOT", obj.getString("parent"));
    JSONArray arr = obj.getJSONArray("listing");
    HashSet<String> hs = new HashSet<String>(arr.length());
    for (int i = 0; i < arr.length(); i++) {
        hs.add(new File(arr.getString(i)).getAbsolutePath());
    }
    for (File d : dirs) {
        // on windows, listRoots returns a bunch of drive names that don't exist
        if (d.exists()) {
            assertTrue(hs.remove(d.getAbsolutePath()));
        }
    }
    assertTrue(hs.isEmpty());

    // lists test resources folder
    File f = new File("src/test/resources/data2");
    get = new GetMethod(URL + "folders/listing?directory=" + URIUtil.encodeQuery(f.getAbsolutePath()));
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    dir = new File(obj.getString("directory"));
    assertEquals(f.getAbsolutePath(), dir.getAbsolutePath());
    assertEquals(f.getParentFile().getAbsolutePath(), dir.getParentFile().getAbsolutePath());
    dirs = dir.listFiles();
    arr = obj.getJSONArray("listing");
    assertEquals(2, arr.length());
    assertEquals(new File("src/test/resources/data2/sub1").getAbsolutePath(), arr.get(0));
    assertEquals(new File("src/test/resources/data2/sub2").getAbsolutePath(), arr.get(1));

    // /folders/add as user: 401
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", "/");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /folders/add : directory does not exist: 404
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", "/does/not/exist");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(404, post.getStatusCode());

    // /folders/add : not a directory: 400
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", new File("src/test/resources/data/1.mp3").getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // /folders/add "/src/test/resources/data"
    f = new File("src/test/resources/data");
    RuntimeStats rt = new RuntimeStats();
    rt.songCount.set(15);
    rt.albumCount.set(5);
    rt.artistCount.set(2);
    rt.playlistCount.set(0);
    rt.userCount.set(2);
    rt.playtime.set(15);
    rt.downloaded.set(0);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // check /folders
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(f.getAbsolutePath(), obj.getJSONArray("folders").getString(0));

    // /folders/add "/src/test/resources/data2/sub1"
    f = new File("src/test/resources/data2/sub1");
    rt.songCount.addAndGet(3);
    rt.albumCount.addAndGet(1);
    rt.artistCount.addAndGet(1);
    rt.playtime.addAndGet(3);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // /folders/add "/src/test/resources/data2/"
    f = new File("src/test/resources/data2/");
    rt.songCount.addAndGet(6);
    rt.playtime.addAndGet(6);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // check /folders
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    arr = obj.getJSONArray("folders");
    assertEquals(3, arr.length());
    for (int i = 0; i < 3; i++) {
        String s = new File(arr.getString(i)).getAbsolutePath();
        String s1 = new File("src/test/resources/data").getAbsolutePath();
        String s2 = new File("src/test/resources/data2/sub1").getAbsolutePath();
        String s3 = new File("src/test/resources/data2").getAbsolutePath();
        assertTrue(s.equals(s1) || s.equals(s2) || s.equals(s3));
    }

    // /folders/remove as user: 401
    post = new PostMethod(URL + "folders/remove");
    post.addParameter("directory[]", "/");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /folders/remove unknown dir: 400
    post = new PostMethod(URL + "folders/remove");
    post.addParameter("directory[]", "/does/not/exist");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // /folders/remove "/src/test/resources/data","src/test/resources/data2"
    post = new PostMethod(URL + "folders/remove");
    f = new File("src/test/resources/data");
    post.addParameter("directory[]", f.getAbsolutePath());
    f = new File("src/test/resources/data2");
    post.addParameter("directory[]", f.getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    rt.songCount.set(3);
    rt.albumCount.set(1);
    rt.artistCount.set(1);
    rt.userCount.set(2);
    rt.playtime.set(3);
    rt.downloaded.set(0);
    this.checkStats(rt);

    // /folders/remove "/src/test/resources/data/sub1"
    post = new PostMethod(URL + "folders/remove");
    f = new File("src/test/resources/data2/sub1");
    post.addParameter("directory[]", f.getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    rt.songCount.set(0);
    rt.albumCount.set(0);
    rt.artistCount.set(0);
    rt.userCount.set(2);
    rt.playtime.set(0);
    rt.downloaded.set(0);
    this.checkStats(rt);

    // /folders: should be empty
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("folders").length());

}

From source file:com.varaneckas.hawkscope.util.OSUtils.java

/**
 * Gets the File System Roots/*  w  w  w .j  av a  2s.  co m*/
 * 
 * @return
 */
public static List<File> getFileSystemRoots() {
    final List<File> roots = new LinkedList<File>();
    switch (CURRENT_OS) {
    case MAC: {
        final File[] volumes = new File("/Volumes").listFiles();
        if (volumes.length == 0) {
            //something's wrong..
            roots.add(new File("/"));
        } else {
            for (final File f : volumes) {
                if (f.canRead() && !isMacApp(f)) {
                    roots.add(f);
                }
            }
        }
        return roots;
    }
    case UNIX:
        roots.add(new File("/"));
        //Ubuntu
        File media = new File("/media");
        if (!media.exists()) {
            //Old School Unix fallback
            media = new File("/mnt");
        }
        if (media.exists()) {
            for (final File f : media.listFiles()) {
                if (f.isDirectory() && f.canRead()) {
                    roots.add(f);
                }
            }
        }
        return roots;
    default: {
        return Arrays.asList(File.listRoots());
    }
    }
}

From source file:me.jdknight.ums.ccml.core.CcmlRootFolderListener.java

/**
 * Parse the meta library for categorizations.
 *//*from   w ww . java  2  s  .co  m*/
private ICustomCategoryMediaLibrary parseMetaLibrary() {
    // Compile a list of shared directories to scan.
    File[] sharedDirectories = LazyCompatibility.getSharedDirectories();
    if (sharedDirectories == null || sharedDirectories.length == 0) {
        sharedDirectories = File.listRoots();
    }

    // Create library.
    ICustomCategoryMediaLibrary library = new CustomCategoryMediaLibrary();
    if (sharedDirectories != null && sharedDirectories.length > 0) {
        for (File sourceDirectory : sharedDirectories) {
            if (sourceDirectory.isDirectory() == true) {
                buildMediaLibrary(library, sourceDirectory);
            }
        }
    }

    return library;
}