下面列出了java.io.File#getFreeSpace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static File getWritableAlbumStorageDir() throws IOException {
if(!isExternalStorageWritable())
throw new IOException("Storage is not writable");
File file = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
RUMBLE_IMAGE_ALBUM_NAME);
if(!file.exists() && !file.mkdirs())
throw new IOException("could not create directory "+file.getAbsolutePath());
if(file.getFreeSpace() < PushStatus.STATUS_ATTACHED_FILE_MAX_SIZE)
throw new IOException("not enough space available ("+file.getFreeSpace()+"/"+PushStatus.STATUS_ATTACHED_FILE_MAX_SIZE+")");
return file;
}
public static List<String> getDisk() {
// ����ϵͳ
List<String> list=new ArrayList<String>();
for (char c = 'A'; c <= 'Z'; c++) {
String dirName = c + ":/";
File win = new File(dirName);
if(win.exists()){
long total=(long)win.getTotalSpace();
long free=(long)win.getFreeSpace();
Double compare=(Double)(1-free*1.0/total)*100;
String str=c+":�� ��ʹ�� "+compare.intValue()+"%";
list.add(str);
}
}
return list;
}
public static double getDiskPartitionSpaceUsedPercent(final String path) {
if (null == path || path.isEmpty())
return -1;
try {
File file = new File(path);
if (!file.exists())
return -1;
long totalSpace = file.getTotalSpace();
if (totalSpace > 0) {
long freeSpace = file.getFreeSpace();
long usedSpace = totalSpace - freeSpace;
return usedSpace / (double) totalSpace;
}
} catch (Exception e) {
return -1;
}
return -1;
}
static void checkThreshold(final String pathName, final Path path, final int threshold, final ComponentLog logger) {
final File file = path.toFile();
final long totalBytes = file.getTotalSpace();
final long freeBytes = file.getFreeSpace();
final long usedBytes = totalBytes - freeBytes;
final double usedPercent = (double) usedBytes / (double) totalBytes * 100D;
if (usedPercent >= threshold) {
final String usedSpace = FormatUtils.formatDataSize(usedBytes);
final String totalSpace = FormatUtils.formatDataSize(totalBytes);
final String freeSpace = FormatUtils.formatDataSize(freeBytes);
final double freePercent = (double) freeBytes / (double) totalBytes * 100D;
final String message = String.format("%1$s exceeds configured threshold of %2$s%%, having %3$s / %4$s (%5$.2f%%) used and %6$s (%7$.2f%%) free",
pathName, threshold, usedSpace, totalSpace, usedPercent, freeSpace, freePercent);
logger.warn(message);
}
}
/**
* Collects some system performance metrics and returns them as ServerStatusMessage which is
* easy to send over JMS.
*
* @param disk
* @return
*/
public static ServerStatusMessage getSystemStats(File disk) {
double load = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
int cores = Runtime.getRuntime().availableProcessors();
int cpuPercents = (int)(load / cores * 100);
java.lang.management.OperatingSystemMXBean mxbean = java.lang.management.ManagementFactory.getOperatingSystemMXBean();
com.sun.management.OperatingSystemMXBean sunmxbean = (com.sun.management.OperatingSystemMXBean) mxbean;
long memFree = sunmxbean.getFreePhysicalMemorySize();
long memTotal = sunmxbean.getTotalPhysicalMemorySize();
long memUsed = memTotal - memFree;
int memPercents = (int)(memUsed / (float) memTotal * 100);
long diskTotal = disk.getTotalSpace();
long diskFree = disk.getFreeSpace();
long diskUsed = diskTotal - diskFree;
int diskPercents = (int)(diskUsed / (float) diskTotal * 100);
ServerStatusMessage statusMessage = new ServerStatusMessage(load, cores, cpuPercents, memUsed, memTotal, memPercents, diskUsed, diskTotal, diskPercents);
return statusMessage;
}
public static double getDiskPartitionSpaceUsedPercent(final String path) {
if (null == path || path.isEmpty())
return -1;
try {
File file = new File(path);
if (!file.exists()) {
boolean result = file.mkdirs();
if (!result) {
}
}
long totalSpace = file.getTotalSpace();
long freeSpace = file.getFreeSpace();
long usedSpace = totalSpace - freeSpace;
if (totalSpace > 0) {
return usedSpace / (double) totalSpace;
}
} catch (Exception e) {
return -1;
}
return -1;
}
@NonNull
private static File createFile(@NonNull final Context context) throws IOException {
final File externalCacheDir = context.getExternalCacheDir();
final File internalCacheDir = context.getCacheDir();
final File cacheDir;
if (externalCacheDir == null && internalCacheDir == null) {
throw new IOException("No cache directory available");
}
if (externalCacheDir == null) {
cacheDir = internalCacheDir;
} else if (internalCacheDir == null) {
cacheDir = externalCacheDir;
} else {
cacheDir = externalCacheDir.getFreeSpace() > internalCacheDir.getFreeSpace() ?
externalCacheDir : internalCacheDir;
}
return File.createTempFile("tmp", TEMP_FILE_SUFFIX, cacheDir);
}
protected boolean hasAvailableStorage(long expectedSize) {
File content = getContentFile();
double totalSpace = (double) content.getTotalSpace();
double freeSpace = (double) content.getFreeSpace();
double percentFull = 100 - ((freeSpace * 100) / totalSpace);
double afterSavedSize = (totalSpace - freeSpace) + expectedSize;
logger.debug("Reporting -> %[{}] Full (download size of [{}] bytes to be added)", percentFull, expectedSize);
// See: https://developer.android.com/training/basics/data-storage/files.html#GetFreeSpace
// If the number returned is a few MB more than the size of the data you want to save, or if the file system is
// less than 90% full, then it's probably safe to proceed. Otherwise, you probably shouldn't write to storage.
return afterSavedSize < totalSpace && percentFull <= 90D;
}
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();
}
@Override
public FsStatus getStatus(Path p) throws IOException {
File partition = pathToFile(p == null ? new Path("/") : p);
//File provides getUsableSpace() and getFreeSpace()
//File provides no API to obtain used space, assume used = total - free
return new FsStatus(partition.getTotalSpace(),
partition.getTotalSpace() - partition.getFreeSpace(),
partition.getFreeSpace());
}
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);
}
public MemoryUsageFigures(@NonNull Context context, @NonNull DocumentFile f) {
String fullPath = getFullPathFromTreeUri(context, f.getUri(), true); // Oh so dirty !!
if (fullPath != null) {
File file = new File(fullPath);
this.freeMemBytes = file.getFreeSpace();
this.totalMemBytes = file.getTotalSpace();
} else {
this.freeMemBytes = 0;
this.totalMemBytes = 0;
}
}
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();
}
/**
* Computes free space on disk where the eviction works.
*
* @return number of available bytes on disk partition.
*/
public long getFreeSpace ()
{
String path = getPath ();
File fpath = new File(path);
return fpath.getFreeSpace ();
}
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");
}
}
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");
}
}
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;
}
}
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;
}
}
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;
}
}
/**
* get the sd card free space
*
* @return the byte of free space
*/
public static long getSdCardFreeSpace() {
File directory = Environment.getExternalStorageDirectory();
return directory.getFreeSpace();
}