java.io.File.getFreeSpace()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.9k)|赞(0)|评价(0)|浏览(198)

本文整理了Java中java.io.File.getFreeSpace()方法的一些代码示例,展示了File.getFreeSpace()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.getFreeSpace()方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:getFreeSpace

File.getFreeSpace介绍

[英]Returns the number of free bytes on the partition containing this path. Returns 0 if this path does not exist.

Note that this is likely to be an optimistic over-estimate and should not be taken as a guarantee your application can actually write this many bytes.
[中]返回包含此路径的分区上的可用字节数。如果此路径不存在,则返回0。
请注意,这可能是一个乐观的过高估计,不应被视为您的应用程序可以实际写入这么多字节的保证。

代码示例

代码示例来源:origin: jenkinsci/jenkins

@Override
  public Long invoke(File f, VirtualChannel channel) throws IOException {
    return f.getFreeSpace();
  }
}

代码示例来源:origin: atomix/atomix

/**
 * Returns the amount of free space remaining.
 *
 * @return the amount of free space remaining
 */
public long getFreeSpace() {
 return file.getFreeSpace();
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

/** @return the total used space on the filesystem in bytes. */
public long getUsed() {
 return dirFile.getTotalSpace() - dirFile.getFreeSpace();
}

代码示例来源:origin: kairosdb/kairosdb

@Override
  public long percentAvailable(File file)
  {
    return Math.round(((double) file.getFreeSpace() / file.getTotalSpace()) * 100);
  }
}

代码示例来源:origin: apache/rocketmq

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;
}

代码示例来源:origin: neo4j/neo4j

private static String getDiskSpace( DatabaseLayout databaseLayout )
{
  File directory = databaseLayout.databaseDirectory();
  long free = directory.getFreeSpace();
  long total = directory.getTotalSpace();
  long percentage = total != 0 ? (free * 100 / total) : 0;
  return String.format( "Disk space on partition (Total / Free / Free %%): %s / %s / %s", total, free, percentage );
}

代码示例来源:origin: Alluxio/alluxio

@Override
public long getSpace(String path, SpaceType type) throws IOException {
 path = stripPath(path);
 File file = new File(path);
 switch (type) {
  case SPACE_TOTAL:
   return file.getTotalSpace();
  case SPACE_FREE:
   return file.getFreeSpace();
  case SPACE_USED:
   return file.getTotalSpace() - file.getFreeSpace();
  default:
   throw new IOException("Unknown space type: " + type);
 }
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

@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());
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

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);
}

代码示例来源:origin: jphp-group/jphp

public static Memory disk_free_space(String path) {
  return LongMemory.valueOf(new File(path).getFreeSpace());
}

代码示例来源:origin: stackoverflow.com

System.out.println("File system root: " + root.getAbsolutePath());
System.out.println("Total space (bytes): " + root.getTotalSpace());
System.out.println("Free space (bytes): " + root.getFreeSpace());
System.out.println("Usable space (bytes): " + root.getUsableSpace());

代码示例来源:origin: Graylog2/graylog2-server

@Override
  public FsStats fsStats() {
    final Map<String, FsStats.Filesystem> filesystems = new HashMap<>(locations.size());

    for (File location : locations) {
      final String path = location.getAbsolutePath();
      final long total = location.getTotalSpace();
      final long free = location.getFreeSpace();
      final long available = location.getUsableSpace();
      final long used = total - free;
      final short usedPercent = (short) ((double) used / total * 100);

      final FsStats.Filesystem filesystem = FsStats.Filesystem.create(
          path, total, free, available, used, usedPercent);

      filesystems.put(path, filesystem);
    }

    return FsStats.create(filesystems);
  }
}

代码示例来源:origin: stackoverflow.com

System.out.println("File system root: " + root.getAbsolutePath());
System.out.println("Total space (bytes): " + root.getTotalSpace());
System.out.println("Free space (bytes): " + root.getFreeSpace());
System.out.println("Usable space (bytes): " + root.getUsableSpace());

代码示例来源:origin: neo4j/neo4j

private void estimateSizeAndCheckAvailableDiskSpace( Path destination,
    DiagnosticsReporterProgress progress, List<DiagnosticsReportSource> sources,
    Path destinationFolder, boolean force ) throws IOException
{
  if ( force )
  {
    return;
  }
  long estimatedFinalSize = 0;
  for ( DiagnosticsReportSource source  : sources )
  {
    estimatedFinalSize += source.estimatedSize( progress );
  }
  long freeSpace = destinationFolder.toFile().getFreeSpace();
  if ( estimatedFinalSize > freeSpace )
  {
    String message = String.format(
        "Free available disk space for %s is %s, worst case estimate is %s. To ignore add '--force' to the command.",
        destination.getFileName(), Format.bytes( freeSpace ), Format.bytes( estimatedFinalSize ) );
    throw new RuntimeException( message );
  }
}

代码示例来源:origin: apache/nifi

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);
    }
  }
}

代码示例来源:origin: apache/incubator-druid

private StorageLocation fakeLocation(long total, long free, long max, Double percent)
{
 File file = EasyMock.mock(File.class);
 EasyMock.expect(file.getTotalSpace()).andReturn(total).anyTimes();
 EasyMock.expect(file.getFreeSpace()).andReturn(free).anyTimes();
 EasyMock.replay(file);
 return new StorageLocation(file, max, percent);
}

代码示例来源:origin: apache/rocketmq

runtimeInfo.put("commitLogDirCapacity", String.format("Total : %s, Free : %s.", MixAll.humanReadableByteCount(commitLogDir.getTotalSpace(), false), MixAll.humanReadableByteCount(commitLogDir.getFreeSpace(), false)));

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldPrintDiskUsage()
{
  // Not sure how to get around this w/o spying. The method that we're unit testing will construct
  // other File instances with this guy as parent and internally the File constructor uses the field 'path'
  // which, if purely mocked, won't be assigned. At the same time we want to control the total/free space methods
  // and what they return... a tough one.
  File storeDir = Mockito.spy( new File( "storeDir" ) );
  DatabaseLayout layout = mock( DatabaseLayout.class );
  when( layout.databaseDirectory() ).thenReturn( storeDir );
  when( storeDir.getTotalSpace() ).thenReturn( 100L );
  when( storeDir.getFreeSpace() ).thenReturn( 40L );
  AssertableLogProvider logProvider = new AssertableLogProvider();
  KernelDiagnostics.StoreFiles storeFiles = new KernelDiagnostics.StoreFiles( layout );
  storeFiles.dump( logProvider.getLog( getClass() ).debugLogger() );
  logProvider.assertContainsMessageContaining( "100 / 40 / 40" );
}

代码示例来源:origin: termux/termux-app

@Override
public Cursor queryRoots(String[] projection) throws FileNotFoundException {
  final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_ROOT_PROJECTION);
  @SuppressWarnings("ConstantConditions") final String applicationName = getContext().getString(R.string.application_name);
  final MatrixCursor.RowBuilder row = result.newRow();
  row.add(Root.COLUMN_ROOT_ID, getDocIdForFile(BASE_DIR));
  row.add(Root.COLUMN_DOCUMENT_ID, getDocIdForFile(BASE_DIR));
  row.add(Root.COLUMN_SUMMARY, null);
  row.add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE | Root.FLAG_SUPPORTS_SEARCH);
  row.add(Root.COLUMN_TITLE, applicationName);
  row.add(Root.COLUMN_MIME_TYPES, ALL_MIME_TYPES);
  row.add(Root.COLUMN_AVAILABLE_BYTES, BASE_DIR.getFreeSpace());
  row.add(Root.COLUMN_ICON, R.drawable.ic_launcher);
  return result;
}

代码示例来源:origin: apache/incubator-druid

boolean canHandle(DataSegment segment)
{
 if (available() < segment.getSize()) {
  log.warn(
    "Segment[%s:%,d] too large for storage[%s:%,d]. Check your druid.segmentCache.locations maxSize param",
    segment.getId(), segment.getSize(), getPath(), available()
  );
  return false;
 }
 if (freeSpaceToKeep > 0) {
  long currFreeSpace = path.getFreeSpace();
  if ((freeSpaceToKeep + segment.getSize()) > currFreeSpace) {
   log.warn(
     "Segment[%s:%,d] too large for storage[%s:%,d] to maintain suggested freeSpace[%d], current freeSpace is [%d].",
     segment.getId(),
     segment.getSize(),
     getPath(),
     available(),
     freeSpaceToKeep,
     currFreeSpace
   );
   return false;
  }
 }
 return true;
}

相关文章