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

The following are Jave code examples for showing how to use getUsableSpace() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: atlas   File: Framework.java   View Source Code Vote up 6 votes
private static File createBundleStorage(String bundleName){
    if(new File(STORAGE_LOCATION).getUsableSpace()>10*1024*1024){
        return new File(STORAGE_LOCATION,bundleName);
    }else{
        File externalStorageDir = null;
        File[] externalStorages = getExternalFilesDirs(RuntimeVariables.androidApplication,"storage");
        if(externalStorages!=null && externalStorages.length>0){
            for(File tmpDir : externalStorages){
                if(tmpDir!=null && getStorageState(tmpDir).equals(Environment.MEDIA_MOUNTED) && tmpDir.getUsableSpace()>20*1024*1024) {
                    externalStorageDir = tmpDir;
                    break;
                }
            }
        }
        if(externalStorageDir!=null){
            return new File(externalStorageDir,bundleName);
        }
    }
    return new File(STORAGE_LOCATION,bundleName);
}
 
Example 2
Project: jdk8u-jdk   File: GetXSpace.java   View Source Code Vote up 6 votes
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 3
Project: openjdk-jdk10   File: GetXSpace.java   View Source Code Vote up 6 votes
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 4
Project: hadoop   File: DirectoryCollection.java   View Source Code Vote up 6 votes
private void setGoodDirsDiskUtilizationPercentage() {

    long totalSpace = 0;
    long usableSpace = 0;

    for (String dir : localDirs) {
      File f = new File(dir);
      if (!f.isDirectory()) {
        continue;
      }
      totalSpace += f.getTotalSpace();
      usableSpace += f.getUsableSpace();
    }
    if (totalSpace != 0) {
      long tmp = ((totalSpace - usableSpace) * 100) / totalSpace;
      if (Integer.MIN_VALUE < tmp && Integer.MAX_VALUE > tmp) {
        goodDirsDiskUtilizationPercentage = (int) tmp;
      }
    } else {
      // got no good dirs
      goodDirsDiskUtilizationPercentage = 0;
    }
  }
 
Example 5
Project: HDImageView   File: ImageCache.java   View Source Code Vote up 5 votes
/**
 * Check how much usable space is available at a given path.
 *
 * @param path The path to check
 * @return The space available in bytes
 */
@TargetApi(VERSION_CODES.GINGERBREAD)
public static long getUsableSpace(File path) {
    if (Utils.hasGingerbread()) {
        return path.getUsableSpace();
    }
    final StatFs stats = new StatFs(path.getPath());
    return stats.getBlockSizeLong() * stats.getAvailableBlocksLong();
}
 
Example 6
Project: atlas   File: FileUtils.java   View Source Code Vote up 5 votes
public static long getUsableSpace(File path) {
    if (path == null) {
        return -1;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        return path.getUsableSpace()/1024/1024;
    } else {
        if (!path.exists()) {
            return 0;
        } else {
            final StatFs stats = new StatFs(path.getPath());
            return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks()/1024/1024;
        }
    }
}
 
Example 7
Project: openjdk-jdk10   File: GetXSpace.java   View Source Code Vote up 5 votes
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 8
Project: Android-Practice   File: ImageCache.java   View Source Code Vote up 5 votes
/**
 * Check how much usable space is available at a given path.
 *
 * @param path The path to check
 * @return The space available in bytes
 */
@TargetApi(VERSION_CODES.GINGERBREAD)
public static long getUsableSpace(File path) {
    if (Utils.hasGingerbread()) {
        return path.getUsableSpace();
    }
    final StatFs stats = new StatFs(path.getPath());
    return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}
 
Example 9
Project: Dragonfly   File: DownSpaceCleaner.java   View Source Code Vote up 5 votes
private long getUsableSpace() {
    long usableSpace = 0;
    try {
        File file = new File(this.path);
        usableSpace = file.getUsableSpace();
    } catch (Exception e) {
        logger.error("E_check {}", type, e);
    }
    return usableSpace;
}
 
Example 10
Project: ftp-server   File: MyFtpServer.java   View Source Code Vote up 5 votes
/**
 * 获取FTP信息
 *
 * @return FTP信息
 * @throws FtpException FTP异常
 */
public FTPInfo getFTPInfo() throws FtpException {
    User userInfo = um.getUserByName(um.getAdminName());
    TransferRateRequest transferRateRequest = (TransferRateRequest) userInfo
            .authorize(new TransferRateRequest());
    File homeDir = Paths.get(userInfo.getHomeDirectory()).toFile();
    long totalSpace = homeDir.getTotalSpace();
    long usedSpace = totalSpace - homeDir.getUsableSpace();

    return new FTPInfo(host, port, homeDir.getAbsolutePath(),
            transferRateRequest.getMaxDownloadRate() / 1024,
            transferRateRequest.getMaxUploadRate() / 1024,
            usedSpace, totalSpace);
}
 
Example 11
Project: DisplayingBitmaps   File: ImageCache.java   View Source Code Vote up 5 votes
/**
 * Check how much usable space is available at a given path.
 *
 * @param path The path to check
 * @return The space available in bytes
 */
@TargetApi(VERSION_CODES.GINGERBREAD)
public static long getUsableSpace(File path) {
    if (Utils.hasGingerbread()) {
        return path.getUsableSpace();
    }
    final StatFs stats = new StatFs(path.getPath());
    return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}
 
Example 12
Project: JkImageLoader   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * get available space
 * @author leibing
 * @createTime 2017/3/2
 * @lastModify 2017/3/2
 * @param path
 * @return
 */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static 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 13
Project: hadoop   File: DirectoryCollection.java   View Source Code Vote up 5 votes
private boolean isDiskUsageOverPercentageLimit(File dir) {
  float freePercentage =
      100 * (dir.getUsableSpace() / (float) dir.getTotalSpace());
  float usedPercentage = 100.0F - freePercentage;
  return (usedPercentage > diskUtilizationPercentageCutoff
      || usedPercentage >= 100.0F);
}
 
Example 14
Project: SigFW   File: DiameterFirewall.java   View Source Code Vote up 4 votes
/**
 * Method to return status of the firewall. 
 * Status can be retrieved over REST API.
 * 
 */
public static String getStatus() {
    String s = "";
    
    s += "Jetty Server Status = " + jettyServer.getState() + "\n";
    s += "Jetty Date = " + jettyServer.getDateField().toString() + "\n";
    s += "Jetty URI = " + jettyServer.getURI().toString() + "\n";
    s += "\n";
    s += "SCTP Associations\n";
    for (Map.Entry<String, Association> a : sctpManagement.getAssociations().entrySet()) {
        s += " Name = " + a.getKey() + "\n";
        s += " Details = " + a.getValue().toString() + "\n";
        s += " isStarted = " + a.getValue().isStarted() + "\n";
        s += " isConnected = " + a.getValue().isConnected() + "\n";
    }
    s += "\n";
    s += "SCTP Servers = " + sctpManagement.getServers().toString() + "\n";
    s += "\n";
    
    s += "OS statistics\n";
    s += " Available processors (cores): " + Runtime.getRuntime().availableProcessors() + "\n";
    s += " Free memory (bytes): " + Runtime.getRuntime().freeMemory() + "\n";
    long maxMemory = Runtime.getRuntime().maxMemory();
    s += " Maximum memory (bytes): " + (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory) + "\n";
    s += " Total memory available to JVM (bytes): " + Runtime.getRuntime().totalMemory() + "\n";
    File[] roots = File.listRoots();
    /* For each filesystem root, print some info */
    for (File root : roots) {
        s += " File system root: " + root.getAbsolutePath() + "\n";
        s += " Total space (bytes): " + root.getTotalSpace() + "\n";
        s += " Free space (bytes): " + root.getFreeSpace() + "\n";
        s += " Usable space (bytes): " + root.getUsableSpace() + "\n";
    }
    s += "\n";
    s += "Network interfaces\n";
    try {
        Enumeration<NetworkInterface> nets;
        nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets)) {
            s += " Display name: " + netint.getDisplayName() + "\n";
            s += " Name: " + netint.getName() + "\n";
            Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
            for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                s += " InetAddress: " + inetAddress + "\n";
            }
        }
    } catch (SocketException ex) {
        java.util.logging.Logger.getLogger(DiameterFirewall.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    return s;
}
 
Example 15
Project: ArtOfAndroid   File: ImageLoadUtil.java   View Source Code Vote up 4 votes
private long getUsableSpace(File path) {
    return path.getUsableSpace();
}
 
Example 16
Project: flume-release-1.7.0   File: LogFile.java   View Source Code Vote up 4 votes
CachedFSUsableSpace(File fs, long interval) {
  this.fs = fs;
  this.interval = interval;
  this.value = new AtomicLong(fs.getUsableSpace());
  this.lastRefresh = new AtomicLong(System.currentTimeMillis());
}
 
Example 17
Project: hadoop   File: TestLocalDirsHandlerService.java   View Source Code Vote up 4 votes
@Test
public void testGetFullDirs() throws Exception {
  Configuration conf = new YarnConfiguration();

  conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077");
  FileContext localFs = FileContext.getLocalFSFileContext(conf);

  String localDir1 = new File(testDir, "localDir1").getPath();
  String localDir2 = new File(testDir, "localDir2").getPath();
  String logDir1 = new File(testDir, "logDir1").getPath();
  String logDir2 = new File(testDir, "logDir2").getPath();
  Path localDir1Path = new Path(localDir1);
  Path logDir1Path = new Path(logDir1);
  FsPermission dirPermissions = new FsPermission((short) 0410);
  localFs.mkdir(localDir1Path, dirPermissions, true);
  localFs.mkdir(logDir1Path, dirPermissions, true);

  conf.set(YarnConfiguration.NM_LOCAL_DIRS, localDir1 + "," + localDir2);
  conf.set(YarnConfiguration.NM_LOG_DIRS, logDir1 + "," + logDir2);
  conf.setFloat(YarnConfiguration.NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE,
    0.0f);
  NodeManagerMetrics nm = NodeManagerMetrics.create();
  LocalDirsHandlerService dirSvc = new LocalDirsHandlerService(nm);
  dirSvc.init(conf);
  Assert.assertEquals(0, dirSvc.getLocalDirs().size());
  Assert.assertEquals(0, dirSvc.getLogDirs().size());
  Assert.assertEquals(1, dirSvc.getDiskFullLocalDirs().size());
  Assert.assertEquals(1, dirSvc.getDiskFullLogDirs().size());
  // check the metrics
  Assert.assertEquals(2, nm.getBadLocalDirs());
  Assert.assertEquals(2, nm.getBadLogDirs());
  Assert.assertEquals(0, nm.getGoodLocalDirsDiskUtilizationPerc());
  Assert.assertEquals(0, nm.getGoodLogDirsDiskUtilizationPerc());

  conf.setFloat(YarnConfiguration.NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE,
    100.0f);
  nm = NodeManagerMetrics.create();
  dirSvc = new LocalDirsHandlerService(nm);
  dirSvc.init(conf);
  Assert.assertEquals(1, dirSvc.getLocalDirs().size());
  Assert.assertEquals(1, dirSvc.getLogDirs().size());
  Assert.assertEquals(0, dirSvc.getDiskFullLocalDirs().size());
  Assert.assertEquals(0, dirSvc.getDiskFullLogDirs().size());
  // check the metrics
  File dir = new File(localDir1);
  int utilizationPerc =
      (int) ((dir.getTotalSpace() - dir.getUsableSpace()) * 100 /
          dir.getTotalSpace());
  Assert.assertEquals(1, nm.getBadLocalDirs());
  Assert.assertEquals(1, nm.getBadLogDirs());
  Assert.assertEquals(utilizationPerc,
    nm.getGoodLocalDirsDiskUtilizationPerc());
  Assert
    .assertEquals(utilizationPerc, nm.getGoodLogDirsDiskUtilizationPerc());

  FileUtils.deleteDirectory(new File(localDir1));
  FileUtils.deleteDirectory(new File(localDir2));
  FileUtils.deleteDirectory(new File(logDir1));
  FileUtils.deleteDirectory(new File(logDir1));
  dirSvc.close();
}
 
Example 18
Project: jdk8u-jdk   File: Basic.java   View Source Code Vote up 4 votes
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 19
Project: lustre-connector-for-hadoop   File: LustreFileSystem.java   View Source Code Vote up 3 votes
/**
 * Returns a status object describing the use and capacity of the
 * file system. If the file system has multiple partitions, the
 * use and capacity of the partition pointed to by the specified
 * path is reflected.
 * @param p Path for which status should be obtained. null means
 * the default partition. 
 * @return a FsStatus object
 * @throws IOException
 *           see specific implementation
 */
@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.getUsableSpace());
}
 
Example 20
Project: JBKWeather   File: ImageLoader.java   View Source Code Vote up 2 votes
/**
 *  获取文件大小
 * @param diskCacheDir
 * @return
 */
private long getUsableSpace(File diskCacheDir) {
    return diskCacheDir.getUsableSpace();
}