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

The following examples show how to use java.io.File#getUsableSpace() .
Example 1
Project: Cotable   File: AppContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the usable storage space.
 *
 * @param path the file path
 * @return the size of usable space
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static long getUsableSpace(File path) {
    if (path == null) {
        return -1;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        return path.getUsableSpace();
    } else {
        if (!path.exists()) {
            return 0;
        } else {
            final StatFs stats = new StatFs(path.getPath());
            return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
        }
    }
}
 
Example 2
Project: cube-sdk   File: DiskFileUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static long getUsedSpace(File path) {
    if (path == null) {
        return -1;
    }

    if (Version.hasGingerbread()) {
        return path.getTotalSpace() - path.getUsableSpace();
    } else {
        if (!path.exists()) {
            return -1;
        } else {
            final StatFs stats = new StatFs(path.getPath());
            return (long) stats.getBlockSize() * (stats.getBlockCount() - stats.getAvailableBlocks());
        }
    }
}
 
Example 3
Project: cloudstack   File: HypervDirectConnectResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
public final void setTestJsonResult(final Map<String, Object> params) {
    File dir = new File((String)params.get("DefaultVirtualDiskFolder"));
    long usableCapacity = dir.getUsableSpace() - 4294967296L;
    long totalSpace = dir.getTotalSpace() - 4294967296L;

    // TODO: add test to verify capacity statistics change
    _setTestJsonResultStr =
        String.format("[{\"com.cloud.agent.api.StartupRoutingCommand\":{" + "\"cpus\":%s," + "\"speed\":%s," + "\"memory\":%s," + "\"dom0MinMemory\":%s,"
            + "\"poolSync\":false," + "\"vms\":{}," + "\"caps\":\"hvm\"," + "\"hypervisorType\":\"Hyperv\"," + "\"hostDetails\":{"
            + "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":" + "\"HostLocal\"" + "}," + "\"type\":\"Routing\"," + "\"dataCenter\":%s," + "\"pod\":%s,"
            + "\"cluster\":%s," + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + "\"name\":\"hypervresource\"," + "\"version\":\"4.2.0\","
            + "\"privateIpAddress\":%s," + "\"privateMacAddress\":%s," + "\"privateNetmask\":%s," + "\"storageIpAddress\":%s," + "\"storageNetmask\":%s,"
            + "\"storageMacAddress\":%s," + "\"gatewayIpAddress\":%s," + "\"contextMap\":{}," + "\"wait\":0" + "}},"
            + "{\"com.cloud.agent.api.StartupStorageCommand\":{" + "\"totalSize\":0," + "\"poolInfo\":{" + "\"uuid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\","
            + "\"host\":%s," + "\"localPath\":%s," + "\"hostPath\":%s," + "\"poolType\":\"Filesystem\"," + "\"capacityBytes\":%s," + "\"availableBytes\":%s" + "},"
            + "\"resourceType\":\"STORAGE_POOL\"," + "\"hostDetails\":{}," + "\"type\":\"Storage\"," + "\"dataCenter\":\"1\"," + "\"guid\":"
            + "\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + "\"contextMap\":{}," + "\"wait\":0" + "}}]", params.get("TestCoreCount"), params.get("TestCoreMhz"),
            params.get("TestMemoryMb"), params.get("TestDom0MinMemoryMb"), s_gson.toJson(params.get("zone")), s_gson.toJson(params.get("pod")),
            s_gson.toJson(params.get("cluster")), s_gson.toJson(params.get("ipaddress")), s_gson.toJson(params.get("private.mac.address")),
            s_gson.toJson(params.get("private.ip.netmask")), s_gson.toJson(params.get("ipaddress")), s_gson.toJson(params.get("private.ip.netmask")),
            s_gson.toJson(params.get("private.mac.address")), s_gson.toJson(params.get("gateway.ip.address")), s_gson.toJson(params.get("ipaddress")),
            s_gson.toJson(params.get("DefaultVirtualDiskFolder")), s_gson.toJson(params.get("DefaultVirtualDiskFolder")), s_gson.toJson(totalSpace),
            s_gson.toJson(usableCapacity));
}
 
Example 4
Project: openjdk-jdk8u   File: GetXSpace.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void compareZeroExist() {
    try {
        File f = File.createTempFile("tmp", null, new File("."));

        long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };

        for (int i = 0; i < s.length; i++) {
            if (s[i] == 0L)
                fail(f.getName(), s[i], "==", 0L);
            else
                pass();
        }
    } catch (IOException x) {
        fail("Couldn't create temp file for test");
    }
}
 
Example 5
Project: openjdk-8-source   File: GetXSpace.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void compareZeroExist() {
    try {
        File f = File.createTempFile("tmp", null, new File("."));

        long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };

        for (int i = 0; i < s.length; i++) {
            if (s[i] == 0L)
                fail(f.getName(), s[i], "==", 0L);
            else
                pass();
        }
    } catch (IOException x) {
        fail("Couldn't create temp file for test");
    }
}
 
Example 6
Project: jdk8u_jdk   File: GetXSpace.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void compareZeroExist() {
    try {
        File f = File.createTempFile("tmp", null, new File("."));

        long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };

        for (int i = 0; i < s.length; i++) {
            if (s[i] == 0L)
                fail(f.getName(), s[i], "==", 0L);
            else
                pass();
        }
    } catch (IOException x) {
        fail("Couldn't create temp file for test");
    }
}
 
Example 7
Project: jdk8u-dev-jdk   File: GetXSpace.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void compareZeroExist() {
    try {
        File f = File.createTempFile("tmp", null, new File("."));

        long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };

        for (int i = 0; i < s.length; i++) {
            if (s[i] == 0L)
                fail(f.getName(), s[i], "==", 0L);
            else
                pass();
        }
    } catch (IOException x) {
        fail("Couldn't create temp file for test");
    }
}
 
Example 8
Project: Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile   File: CheckDiskspace.java    License: MIT License 5 votes vote down vote up
private void checkDiskspace(HealthCheckResponseBuilder builder) {
    File root = new File(pathToMonitor);
    long usableSpace = root.getUsableSpace();
    long freeSpace = root.getFreeSpace();
    long pctFree = 0;
    if (usableSpace > 0) {
        pctFree = (100 * usableSpace) / freeSpace;
    }
    builder.withData("path", root.getAbsolutePath())
            .withData("exits", root.exists())
            .withData("usableSpace", usableSpace)
            .withData("freeSpace", freeSpace)
            .withData("pctFree", pctFree)
            .state(freeSpace >= freeSpaceThreshold);
}
 
Example 9
Project: android_9.0.0_r45   File: OtaDexoptService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the difference of free space to the low-storage-space threshold. Positive values
 * indicate free bytes.
 */
private long getAvailableSpace() {
    // TODO: If apps are not installed in the internal /data partition, we should compare
    //       against that storage's free capacity.
    long lowThreshold = getMainLowSpaceThreshold();

    File dataDir = Environment.getDataDirectory();
    long usableSpace = dataDir.getUsableSpace();

    return usableSpace - lowThreshold;
}
 
Example 10
Project: Cirrus_depricated   File: FileStorageUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressLint("NewApi")
public static final long getUsableSpace(String accountName) {
    File savePath = Environment.getExternalStorageDirectory();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
        return savePath.getUsableSpace();

    } else {
        StatFs stats = new StatFs(savePath.getAbsolutePath());
        return stats.getAvailableBlocks() * stats.getBlockSize();
    }

}
 
Example 11
Project: CombineBitmap   File: DiskLruCacheHelper.java    License: Apache License 2.0 5 votes vote down vote up
private long getUsableSpace(File path) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        return path.getUsableSpace();
    }
    final StatFs stats = new StatFs(path.getPath());
    return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}
 
Example 12
Project: jdk8u_jdk   File: GetXSpace.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void compare(Space s) {
    File f = new File(s.name());
    long ts = f.getTotalSpace();
    long fs = f.getFreeSpace();
    long us = f.getUsableSpace();

    out.format("%s:%n", s.name());
    String fmt = "  %-4s total= %12d free = %12d usable = %12d%n";
    out.format(fmt, "df", s.total(), 0, s.free());
    out.format(fmt, "getX", ts, fs, us);

    // if the file system can dynamically change size, this check will fail
    if (ts != s.total())
        fail(s.name(), s.total(), "!=", ts);
    else
        pass();

    // unix df returns statvfs.f_bavail
    long tsp = (!name.startsWith("Windows") ? us : fs);
    if (!s.woomFree(tsp))
        fail(s.name(), s.free(), "??", tsp);
    else
        pass();

    if (fs > s.total())
        fail(s.name(), s.total(), ">", fs);
    else
        pass();

    if (us > s.total())
        fail(s.name(), s.total(), ">", us);
    else
        pass();
}
 
Example 13
Project: XRTB   File: Performance.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the percentage of free disk
 * 
 * @return String. The string representation of free disk as a percentage of
 *         the whole.
 */
public static String getPercFreeDisk() {

	File file = new File("/");

	long totalSpace = file.getTotalSpace(); // total disk space in bytes.
	long usableSpace = file.getUsableSpace(); /// unallocated / free disk
												/// space in bytes.
	long freeSpace = file.getFreeSpace(); // unallocated / free disk space
											// in bytes.

	double percent = (double) freeSpace / (double) totalSpace * 100;
	return formatter.format(percent);
}
 
Example 14
Project: DeconvolutionLab2   File: SystemUsage.java    License: GNU General Public License v3.0 4 votes vote down vote up
public static double getAvailableSpace() {
	File[] roots = File.listRoots();
	for(File root : roots)
		return root.getUsableSpace();
	return 0;
}
 
Example 15
Project: android_9.0.0_r45   File: StorageManagerService.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public long getAllocatableBytes(String volumeUuid, int flags, String callingPackage) {
    flags = adjustAllocateFlags(flags, Binder.getCallingUid(), callingPackage);

    final StorageManager storage = mContext.getSystemService(StorageManager.class);
    final StorageStatsManager stats = mContext.getSystemService(StorageStatsManager.class);
    final long token = Binder.clearCallingIdentity();
    try {
        // In general, apps can allocate as much space as they want, except
        // we never let them eat into either the minimum cache space or into
        // the low disk warning space. To avoid user confusion, this logic
        // should be kept in sync with getFreeBytes().
        final File path = storage.findPathForUuid(volumeUuid);

        final long usable = path.getUsableSpace();
        final long lowReserved = storage.getStorageLowBytes(path);
        final long fullReserved = storage.getStorageFullBytes(path);

        if (stats.isQuotaSupported(volumeUuid)) {
            final long cacheTotal = stats.getCacheBytes(volumeUuid);
            final long cacheReserved = storage.getStorageCacheBytes(path, flags);
            final long cacheClearable = Math.max(0, cacheTotal - cacheReserved);

            if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
                return Math.max(0, (usable + cacheClearable) - fullReserved);
            } else {
                return Math.max(0, (usable + cacheClearable) - lowReserved);
            }
        } else {
            // When we don't have fast quota information, we ignore cached
            // data and only consider unused bytes.
            if ((flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0) {
                return Math.max(0, usable - fullReserved);
            } else {
                return Math.max(0, usable - lowReserved);
            }
        }
    } catch (IOException e) {
        throw new ParcelableException(e);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example 16
Project: jdk8u-jdk   File: Basic.java    License: GNU General Public License v2.0 4 votes vote down vote up
static void doTests(Path dir) throws IOException {
    /**
     * Test: Directory should be on FileStore that is writable
     */
    assertTrue(!Files.getFileStore(dir).isReadOnly());

    /**
     * Test: Two files should have the same FileStore
     */
    Path file1 = Files.createFile(dir.resolve("foo"));
    Path file2 = Files.createFile(dir.resolve("bar"));
    FileStore store1 = Files.getFileStore(file1);
    FileStore store2 = Files.getFileStore(file2);
    assertTrue(store1.equals(store2));
    assertTrue(store2.equals(store1));
    assertTrue(store1.hashCode() == store2.hashCode());

    /**
     * Test: File and FileStore attributes
     */
    assertTrue(store1.supportsFileAttributeView("basic"));
    assertTrue(store1.supportsFileAttributeView(BasicFileAttributeView.class));
    assertTrue(store1.supportsFileAttributeView("posix") ==
        store1.supportsFileAttributeView(PosixFileAttributeView.class));
    assertTrue(store1.supportsFileAttributeView("dos") ==
        store1.supportsFileAttributeView(DosFileAttributeView.class));
    assertTrue(store1.supportsFileAttributeView("acl") ==
        store1.supportsFileAttributeView(AclFileAttributeView.class));
    assertTrue(store1.supportsFileAttributeView("user") ==
        store1.supportsFileAttributeView(UserDefinedFileAttributeView.class));

    /**
     * Test: Space atributes
     */
    File f = file1.toFile();
    long total = f.getTotalSpace();
    long free = f.getFreeSpace();
    long usable = f.getUsableSpace();

    // check values are "close"
    checkWithin1GB(total,  store1.getTotalSpace());
    checkWithin1GB(free,   store1.getUnallocatedSpace());
    checkWithin1GB(usable, store1.getUsableSpace());

    // get values by name
    checkWithin1GB(total,  (Long)store1.getAttribute("totalSpace"));
    checkWithin1GB(free,   (Long)store1.getAttribute("unallocatedSpace"));
    checkWithin1GB(usable, (Long)store1.getAttribute("usableSpace"));

    /**
     * Test: Enumerate all FileStores
     */
    FileStore prev = null;
    for (FileStore store: FileSystems.getDefault().getFileStores()) {
        System.out.format("%s (name=%s type=%s)\n", store, store.name(),
            store.type());

        // check space attributes are accessible
        store.getTotalSpace();
        store.getUnallocatedSpace();
        store.getUsableSpace();

        // two distinct FileStores should not be equal
        assertTrue(!store.equals(prev));
        prev = store;
    }
}
 
Example 17
Project: TencentKona-8   File: Basic.java    License: GNU General Public License v2.0 4 votes vote down vote up
static void doTests(Path dir) throws IOException {
    /**
     * Test: Directory should be on FileStore that is writable
     */
    assertTrue(!Files.getFileStore(dir).isReadOnly());

    /**
     * Test: Two files should have the same FileStore
     */
    Path file1 = Files.createFile(dir.resolve("foo"));
    Path file2 = Files.createFile(dir.resolve("bar"));
    FileStore store1 = Files.getFileStore(file1);
    FileStore store2 = Files.getFileStore(file2);
    assertTrue(store1.equals(store2));
    assertTrue(store2.equals(store1));
    assertTrue(store1.hashCode() == store2.hashCode());

    /**
     * Test: File and FileStore attributes
     */
    assertTrue(store1.supportsFileAttributeView("basic"));
    assertTrue(store1.supportsFileAttributeView(BasicFileAttributeView.class));
    assertTrue(store1.supportsFileAttributeView("posix") ==
        store1.supportsFileAttributeView(PosixFileAttributeView.class));
    assertTrue(store1.supportsFileAttributeView("dos") ==
        store1.supportsFileAttributeView(DosFileAttributeView.class));
    assertTrue(store1.supportsFileAttributeView("acl") ==
        store1.supportsFileAttributeView(AclFileAttributeView.class));
    assertTrue(store1.supportsFileAttributeView("user") ==
        store1.supportsFileAttributeView(UserDefinedFileAttributeView.class));

    /**
     * Test: Space atributes
     */
    File f = file1.toFile();
    long total = f.getTotalSpace();
    long free = f.getFreeSpace();
    long usable = f.getUsableSpace();

    // check values are "close"
    checkWithin1GB(total,  store1.getTotalSpace());
    checkWithin1GB(free,   store1.getUnallocatedSpace());
    checkWithin1GB(usable, store1.getUsableSpace());

    // get values by name
    checkWithin1GB(total,  (Long)store1.getAttribute("totalSpace"));
    checkWithin1GB(free,   (Long)store1.getAttribute("unallocatedSpace"));
    checkWithin1GB(usable, (Long)store1.getAttribute("usableSpace"));

    /**
     * Test: Enumerate all FileStores
     */
    if (FileUtils.areFileSystemsAccessible()) {
        FileStore prev = null;
        for (FileStore store: FileSystems.getDefault().getFileStores()) {
            System.out.format("%s (name=%s type=%s)\n", store, store.name(),
                store.type());

            // check space attributes are accessible
            try {
                store.getTotalSpace();
                store.getUnallocatedSpace();
                store.getUsableSpace();
            } catch (NoSuchFileException nsfe) {
                // ignore exception as the store could have been
                // deleted since the iterator was instantiated
                System.err.format("%s was not found\n", store);
            } catch (AccessDeniedException ade) {
                // ignore exception as the lack of ability to access the
                // store due to lack of file permission or similar does not
                // reflect whether the space attributes would be accessible
                // were access to be permitted
                System.err.format("%s is inaccessible\n", store);
            }

            // two distinct FileStores should not be equal
            assertTrue(!store.equals(prev));
            prev = store;
        }
    } else {
        System.err.println
            ("Skipping FileStore check due to file system access failure");
    }
}
 
Example 18
Project: cosmic   File: JavaStorageLayer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public long getUsableSpace(final String path) {
    final File file = new File(path);
    return file.getUsableSpace();
}
 
Example 19
Project: big-c   File: DirectoryCollection.java    License: Apache License 2.0 4 votes vote down vote up
private boolean isDiskFreeSpaceUnderLimit(File dir) {
  long freeSpace = dir.getUsableSpace() / (1024 * 1024);
  return freeSpace < this.diskUtilizationSpaceCutoff;
}
 
Example 20
Project: android_9.0.0_r45   File: StorageManager.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Return the number of available bytes until the given path is considered
 * running low on storage.
 *
 * @hide
 */
public long getStorageBytesUntilLow(File path) {
    return path.getUsableSpace() - getStorageFullBytes(path);
}