Java Code Examples for org.apache.commons.io.FileUtils#sizeOf()

The following examples show how to use org.apache.commons.io.FileUtils#sizeOf() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileDownloader.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 本地文件下载
 *
 * @param file
 * @param response
 * @return
 * @throws IOException
 */
public static boolean writeLocalFile(File file, HttpServletResponse response) throws IOException {
       if (!file.exists()) {
           response.setHeader("Content-Disposition", StringUtils.EMPTY);  // Clean download
           response.sendError(HttpServletResponse.SC_NOT_FOUND);
           return false;
       }

	long size = FileUtils.sizeOf(file);
	response.setHeader("Content-Length", String.valueOf(size));

	try (InputStream fis = new FileInputStream(file)) {
		response.setContentLength(fis.available());

		OutputStream os = response.getOutputStream();
		int count;
		byte[] buffer = new byte[1024 * 1024];
		while ((count = fis.read(buffer)) != -1) {
			os.write(buffer, 0, count);
		}
		os.flush();
		return true;
	}
}
 
Example 2
Source File: ExtractorUtils.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/****
 * Gets the size of the largest disk-store in a directory 
 * @param diskStores List of diskstores
 * @param diskStoreDirPath path of the directory where the disk-store are created
 * @return size of the largest disk-store
 */
public static long getMaxDiskStoreSizeInDir(List<DiskStoreImpl> diskStores, String diskStoreDirPath) {
  File diskStoreDir = new File(diskStoreDirPath);
  long maxDiskStoreSizeOnDisk =0;
  for (DiskStoreImpl diskStore : diskStores) {
    String[] fileNames = diskStoreDir.list(new DiskStoreNameFilter(diskStore.getName()));
    long diskStoreSize = 0;

    if (fileNames != null && fileNames.length > 0) {
      for (String fileName : fileNames) {
        File file = new File(FilenameUtils.concat(diskStoreDirPath, fileName));
        if (file.exists()) {
          diskStoreSize += FileUtils.sizeOf(file); 
        }
      }
    }

    if (maxDiskStoreSizeOnDisk < diskStoreSize) {
      maxDiskStoreSizeOnDisk = diskStoreSize;
    }
  }
  return maxDiskStoreSizeOnDisk;
}
 
Example 3
Source File: ObjectStoreFileStorageTest.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
private String addBlobWithNoMetadata() throws Exception {
    BlobStore blobStore = blobStoreContext.getBlobStore();
    Path path = Paths.get(TEST_FILE_LOCATION);
    long fileSize = FileUtils.sizeOf(path.toFile());
    String id = UUID.randomUUID()
                    .toString();
    Blob blob = blobStore.blobBuilder(id)
                         .payload(new FileInputStream(path.toFile()))
                         .contentDisposition(path.getFileName()
                                                 .toString())
                         .contentType(MediaType.OCTET_STREAM.toString())
                         .contentLength(fileSize)
                         .build();
    blobStore.putBlob(CONTAINER, blob);
    return id;
}
 
Example 4
Source File: TestBookKeeper.java    From rubix with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the metric representing the current cache size is correctly registered & reports expected values.
 *
 * @throws IOException if an I/O error occurs when interacting with the cache.
 */
@Test
public void verifyCacheSizeMetricIsReported() throws IOException, TException
{
  final String remotePathWithScheme = "file://" + TEST_REMOTE_PATH;
  final int readOffset = 0;
  final int readLength = 100;

  // Since the value returned from a gauge metric is an object rather than a primitive, boxing is required here to properly compare the values.
  assertEquals(metrics.getGauges().get(BookKeeperMetrics.CacheMetric.CACHE_SIZE_GAUGE.getMetricName()).getValue(), 0);

  DataGen.populateFile(TEST_REMOTE_PATH);
  bookKeeper.readData(remotePathWithScheme, readOffset, readLength, TEST_FILE_LENGTH, TEST_LAST_MODIFIED, ClusterType.TEST_CLUSTER_MANAGER.ordinal());

  final long mdSize = FileUtils.sizeOf(new File(CacheUtil.getMetadataFilePath(TEST_REMOTE_PATH, conf)));
  final int totalCacheSize = (int) BYTES.toMB(readLength + mdSize);
  assertEquals(metrics.getGauges().get(BookKeeperMetrics.CacheMetric.CACHE_SIZE_GAUGE.getMetricName()).getValue(), totalCacheSize);
}
 
Example 5
Source File: ExtractorUtils.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/****
 * Gets the size of the largest disk-store in a directory 
 * @param diskStores List of diskstores
 * @param diskStoreDirPath path of the directory where the disk-store are created
 * @return size of the largest disk-store
 */
public static long getMaxDiskStoreSizeInDir(List<DiskStoreImpl> diskStores, String diskStoreDirPath) {
  File diskStoreDir = new File(diskStoreDirPath);
  long maxDiskStoreSizeOnDisk =0;
  for (DiskStoreImpl diskStore : diskStores) {
    String[] fileNames = diskStoreDir.list(new DiskStoreNameFilter(diskStore.getName()));
    long diskStoreSize = 0;

    if (fileNames != null && fileNames.length > 0) {
      for (String fileName : fileNames) {
        File file = new File(FilenameUtils.concat(diskStoreDirPath, fileName));
        if (file.exists()) {
          diskStoreSize += FileUtils.sizeOf(file); 
        }
      }
    }

    if (maxDiskStoreSizeOnDisk < diskStoreSize) {
      maxDiskStoreSizeOnDisk = diskStoreSize;
    }
  }
  return maxDiskStoreSizeOnDisk;
}
 
Example 6
Source File: IOHelper.java    From Kernel-Tuner with GNU General Public License v3.0 5 votes vote down vote up
public static long sizeOf(File file)
{
    try
    {
        return FileUtils.sizeOf(file);
    }
    catch (Exception e)
    {
        return 0;
    }
}
 
Example 7
Source File: Tar.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
List<File> uncompressTarXzFile(File inputFile, File outputDir, Consumer<ProgressEntity> stateCallback) {
    try (CountingInputStream countingInputStream = new CountingInputStream(new FileInputStream(inputFile));
            InputStream inputStream = new XZCompressorInputStream(countingInputStream)) {
        final long finalSize = FileUtils.sizeOf(inputFile);
        return uncompress(inputStream, countingInputStream, outputDir, finalSize, stateCallback);
    } catch (IOException e) {
        throw new ArchiveException(TAR_ERROR_MESSAGE, e);
    }
}
 
Example 8
Source File: Tar.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
List<File> uncompressTarGzFile(File inputFile, File outputDir, Consumer<ProgressEntity> stateCallback) {
    try (CountingInputStream countingInputStream = new CountingInputStream(new FileInputStream(inputFile));
            InputStream inputStream = new GZIPInputStream(countingInputStream)) {
        final long finalSize = FileUtils.sizeOf(inputFile);
        return uncompress(inputStream, countingInputStream, outputDir, finalSize, stateCallback);
    } catch (IOException e) {
        throw new ArchiveException(TAR_ERROR_MESSAGE, e);
    }
}
 
Example 9
Source File: Tar.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
List<File> uncompressTarBz2File(File inputFile, File outputDir, Consumer<ProgressEntity> stateCallback) {
    try (CountingInputStream countingInputStream = new CountingInputStream(new FileInputStream(inputFile));
            InputStream inputStream = new BZip2CompressorInputStream(countingInputStream)) {
        final long finalSize = FileUtils.sizeOf(inputFile);
        return uncompress(inputStream, countingInputStream, outputDir, finalSize, stateCallback);
    } catch (IOException e) {
        throw new ArchiveException(TAR_ERROR_MESSAGE, e);
    }
}
 
Example 10
Source File: Zip.java    From phoenicis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<File> uncompressZipFile(File inputFile, File outputDir, Consumer<ProgressEntity> stateCallback) {
    LOGGER.info(String.format("Attempting to unzip file \"%s\" to directory \"%s\".",
            inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

    final Path targetDirPath = outputDir.toPath();

    try (ZipFile zipFile = new ZipFile(inputFile)) {
        final long finalSize = FileUtils.sizeOf(inputFile);

        final AtomicLong extractedBytesCounter = new AtomicLong(0);
        final Consumer<ZipExtractionResult> unzipCallback = zipExtractionResult -> {
            final double currentExtractedBytes = extractedBytesCounter
                    .addAndGet(zipExtractionResult.getExtractedBytes());

            stateCallback
                    .accept(new ProgressEntity.Builder()
                            .withPercent(currentExtractedBytes / finalSize * 100.0D)
                            .withProgressText(tr("Extracted {0}", zipExtractionResult.getFileName())).build());
        };

        return Collections.list(zipFile.getEntries()).stream()
                .map(entry -> unzipEntry(zipFile, entry, targetDirPath, unzipCallback))
                .collect(Collectors.toList());
    } catch (IOException e) {
        throw new ArchiveException(ZIP_ERROR_MESSAGE, e);
    }
}
 
Example 11
Source File: JavaFileSizeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() {
    final File file = new File(filePath);

    final long size = FileUtils.sizeOf(file);

    assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, size);
}
 
Example 12
Source File: ObjectStoreFileStorageTest.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private FileEntry enrichFileEntry(FileEntry fileEntry, Path path, Date date) {
    long sizeOfFile = FileUtils.sizeOf(path.toFile());
    BigInteger bigInteger = BigInteger.valueOf(sizeOfFile);
    return ImmutableFileEntry.builder()
                             .from(fileEntry)
                             .size(bigInteger)
                             .modified(date != null ? date : new Date(System.currentTimeMillis()))
                             .name(path.getFileName()
                                       .toString())
                             .build();
}
 
Example 13
Source File: LocalPinotFS.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Override
public long length(URI fileUri) {
  File file = toFile(fileUri);
  if (file.isDirectory()) {
    throw new IllegalArgumentException("File is directory");
  }
  return FileUtils.sizeOf(file);
}
 
Example 14
Source File: Utils.java    From webdriverextensions-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static String readableFileSize(File file) {
    long size = FileUtils.sizeOf(file);
    if (size <= 0) {
        return "0";
    }

    final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
    int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
    return StringUtils.leftPad(new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)), 8) + " " + units[digitGroups];
}
 
Example 15
Source File: ImageUtil.java    From newblog with Apache License 2.0 5 votes vote down vote up
public static File thimage(File file) {
    try {
        System.out.println(FileUtils.sizeOf(file));
        if (FileUtils.sizeOf(file) < 2000 * 1000) {
            return file;
        }
        Thumbnails.of(file).scale(1f).outputQuality(0.25f).toFile(file);
    } catch (Exception e) {
        logger.error("图片缩放错误:" + e);
    }
    return file;
}
 
Example 16
Source File: DefaultFSSinkProvider.java    From ambari-metrics with Apache License 2.0 5 votes vote down vote up
private boolean shouldReCreate(File f) {
  if (!f.exists()) {
    return true;
  }
  if (FileUtils.sizeOf(f) > FIXED_FILE_SIZE) {
    return true;
  }
  return false;
}
 
Example 17
Source File: SQLLiteDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
@Override
public long getDBSize() {
	return FileUtils.sizeOf(getFile(SERVERNAME));
}
 
Example 18
Source File: FileDAO.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
@Override
public long getDBSize() {
	return FileUtils.sizeOf(directory);
}
 
Example 19
Source File: Utils.java    From webdriverextensions-maven-plugin with Apache License 2.0 4 votes vote down vote up
public static boolean validateFileIsLargerThanBytes(Path filePath, int bytes) {
    return FileUtils.sizeOf(filePath.toFile()) > bytes;
}
 
Example 20
Source File: StoreEngine.java    From sofa-jraft with Apache License 2.0 4 votes vote down vote up
public long getStoreUsedSpace() {
    if (this.dbPath == null || !this.dbPath.exists()) {
        return 0;
    }
    return FileUtils.sizeOf(this.dbPath);
}