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

The following are Jave code examples for showing how to use getTotalSpace() 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: 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 2
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: UtilAll.java   View Source Code Vote up 6 votes
/**
 * 获取磁盘分区空间使用率
 */
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;
}
 
Example 3
Project: reading-and-annotate-rocketmq-3.4.6   File: UtilAll.java   View Source Code Vote up 6 votes
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) {
                // TODO
            }
        }

        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;
}
 
Example 4
Project: retroxlibs   File: DriveUtils.java   View Source Code Vote up 6 votes
private static String createSignature(File dir) {
	List<String> fileNames = new ArrayList<String>();
	File files[] = dir.listFiles();
	if (files!=null) {
		for(File file : files) fileNames.add(file.getName());
	}

	Collections.sort(fileNames);
	StringBuffer fileNamesText = new StringBuffer();
	for(String fileName : fileNames) {
		fileNamesText.append(fileName);
	}

	Log.d(LOGTAG, "signature for root " + dir.getAbsolutePath() + " input " + fileNamesText.toString());
	String signature = Utils.md5(fileNamesText.toString()) + "." + dir.getTotalSpace();
	Log.d(LOGTAG, "signature for root " + dir.getAbsolutePath() + " = " + signature);
	return signature;
}
 
Example 5
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 6
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 7
Project: rmq4note   File: UtilAll.java   View Source Code Vote up 6 votes
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;
}
 
Example 8
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 9
Project: jdk8u-jdk   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 10
Project: hadoop-oss   File: DUHelper.java   View Source Code Vote up 5 votes
public String check(String folder) {
  if (folder == null)
    throw new IllegalArgumentException("folder");
  File f = new File(folder);

  folderSize = getFileSize(f);
  usage = 1.0*(f.getTotalSpace() - f.getFreeSpace())/ f.getTotalSpace();
  return String.format("used %d files %d disk in use %f", folderSize, fileCount, usage);
}
 
Example 11
Project: Android-FileBrowser-FilePicker   File: AssortedUtils.java   View Source Code Vote up 5 votes
public static long GetMinimumDirSize(File file)
{
	long result = 0;
	for( File f : file.listFiles()) {
		if(f.isFile()) {
			result += f.length();
		} else if(f.isDirectory()) {
			result += f.getTotalSpace();
		}
	}
	return result;
}
 
Example 12
Project: Dragonfly   File: DiskSpaceGcTimer.java   View Source Code Vote up 5 votes
@PostConstruct
public void init() {
    long totalSpace = 0;
    try {
        File file = new File(Constants.DOWNLOAD_HOME);
        totalSpace = file.getTotalSpace();
    } catch (Exception e) {
    }
    long youngGcThreshold = totalSpace > 0 && totalSpace / 4 < 100 * 1024 * 1024 * 1024L ? totalSpace / 4
        : 100 * 1024 * 1024 * 1024L;
    downSpaceCleaner.fillConf(DownSpaceCleaner.SPACE_TYPE_DISK, Constants.DOWNLOAD_HOME,
        5 * 1024 * 1024 * 1024L,
        youngGcThreshold, 1, 2 * 3600 * 1000L);
}
 
Example 13
Project: letv   File: SystemUtils.java   View Source Code Vote up 5 votes
public static String getExternalImageCacheDir(Context context) {
    String coolcloudDir = System.getProperty("file.separator") + context.getPackageName() + System.getProperty("file.separator");
    String androidDataDir = System.getProperty("file.separator") + "Android" + System.getProperty("file.separator") + ShareRequestParam.RESP_UPLOAD_PIC_PARAM_DATA;
    String externalCacheDir = null;
    String[] paths = getVolumePaths(context);
    if (paths != null && paths.length >= 2) {
        if (paths[1].contains("udisk")) {
            if (1 == isSdcardMounted(paths[0], context)) {
                externalCacheDir = paths[0] + androidDataDir + coolcloudDir;
            }
        } else if (1 == isSdcardMounted(paths[1], context)) {
            externalCacheDir = paths[1] + androidDataDir + coolcloudDir;
        }
    }
    if (externalCacheDir == null) {
        if (Environment.getExternalStorageState().equals("mounted")) {
            externalCacheDir = Environment.getExternalStorageDirectory().getPath() + androidDataDir + coolcloudDir;
        } else {
            File file = context.getFilesDir();
            String udiskDir = file.getAbsolutePath();
            if (VERSION.SDK_INT > 8) {
                if (file != null && file.exists() && file.getTotalSpace() > 0) {
                    externalCacheDir = udiskDir + androidDataDir + coolcloudDir;
                }
            } else if (file != null && file.isDirectory()) {
                externalCacheDir = udiskDir + androidDataDir + coolcloudDir;
            }
        }
    }
    if (externalCacheDir == null) {
        return "";
    }
    new File(externalCacheDir).mkdirs();
    return externalCacheDir;
}
 
Example 14
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 15
Project: MetadataEditor   File: EStorageItemsLister.java   View Source Code Vote up 5 votes
private static String getRootOfInnerSdCardFolder(File file)
{
    if(file==null)
        return null;
    final long totalSpace=file.getTotalSpace();
    while(true)
    {
        final File parentFile=file.getParentFile();
        if(parentFile==null||parentFile.getTotalSpace()!=totalSpace)
            return file.getAbsolutePath();
        file=parentFile;
    }
}
 
Example 16
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 17
Project: hadoop   File: RawLocalFileSystem.java   View Source Code Vote up 5 votes
@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());
}
 
Example 18
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 19
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 20
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());
}