java.io.File#getUsableSpace ( )源码实例Demo

下面列出了java.io.File#getUsableSpace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Cotable   文件: AppContext.java
/**
 * 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();
        }
    }
}
 
源代码2 项目: cube-sdk   文件: DiskFileUtils.java
@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());
        }
    }
}
 
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));
}
 
源代码4 项目: openjdk-jdk8u   文件: GetXSpace.java
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");
    }
}
 
源代码5 项目: openjdk-8-source   文件: GetXSpace.java
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");
    }
}
 
源代码6 项目: jdk8u_jdk   文件: GetXSpace.java
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");
    }
}
 
源代码7 项目: jdk8u-dev-jdk   文件: GetXSpace.java
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");
    }
}
 
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);
}
 
源代码9 项目: android_9.0.0_r45   文件: OtaDexoptService.java
/**
 * 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;
}
 
源代码10 项目: Cirrus_depricated   文件: FileStorageUtils.java
@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();
    }

}
 
源代码11 项目: CombineBitmap   文件: DiskLruCacheHelper.java
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();
}
 
源代码12 项目: jdk8u_jdk   文件: GetXSpace.java
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();
}
 
源代码13 项目: XRTB   文件: Performance.java
/**
 * 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);
}
 
源代码14 项目: DeconvolutionLab2   文件: SystemUsage.java
public static double getAvailableSpace() {
	File[] roots = File.listRoots();
	for(File root : roots)
		return root.getUsableSpace();
	return 0;
}
 
源代码15 项目: android_9.0.0_r45   文件: StorageManagerService.java
@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);
    }
}
 
源代码16 项目: jdk8u-jdk   文件: Basic.java
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;
    }
}
 
源代码17 项目: TencentKona-8   文件: Basic.java
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");
    }
}
 
源代码18 项目: cosmic   文件: JavaStorageLayer.java
@Override
public long getUsableSpace(final String path) {
    final File file = new File(path);
    return file.getUsableSpace();
}
 
源代码19 项目: big-c   文件: DirectoryCollection.java
private boolean isDiskFreeSpaceUnderLimit(File dir) {
  long freeSpace = dir.getUsableSpace() / (1024 * 1024);
  return freeSpace < this.diskUtilizationSpaceCutoff;
}
 
源代码20 项目: android_9.0.0_r45   文件: StorageManager.java
/**
 * 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);
}