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

The following are Jave code examples for showing how to use getFreeSpace() 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: Ships   File: HttpCacheTileServer.java   View Source Code Vote up 6 votes
private void retrieveCacheDir(final Context context) {
	final String tag="retrieveCacheDir - ";
	dirCache = null;
	if (isExternalStorageWritable()){
		final File dir=new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),DIRECTORY_TILES_CACHE);
		if (!dir.exists()) {
			try {
				if (!dir.mkdirs()){
					Log.w(TAG,tag+"Not possible to create directory: "+ dir.getPath());
				} else {
					dirCache=dir;
				}
			} catch (SecurityException e){
				Log.w(TAG,tag+"Not possible to create directory: "+ dir.getPath(),e);
			}
		} else if (dir.getFreeSpace()<MIN_FREE_BYTES){
			Log.w(TAG,tag+"Not enough free space on external files dir. Minimal required: "+MIN_FREE_BYTES+" bytes.");
		} else {
			dirCache=dir;
		}
	}

	if (dirCache==null){
		Log.w(TAG,tag+"No external files directory available, use cache directory.");
		dirCache = context.getCacheDir();
	}
}
 
Example 2
Project: nectar-server   File: FTSController.java   View Source Code Vote up 6 votes
private boolean checkSpace(long size) {
    File ftsDir = new File(NectarServerApplication.getConfiguration().getFtsDirectory());

    long usableSpace = (ftsDir.getFreeSpace() / 1000) / 1000;
    if(usableSpace <= NectarServerApplication.getConfiguration().getSpaceThreshold()) {
        NectarServerApplication.getLogger().warn("FTS Directory only has " + usableSpace + "MB of free space left!");
        return false;
    }

    long sizeMb = size / 1000 / 1000;
    if(usableSpace <= sizeMb) {
        NectarServerApplication.getLogger().warn("Rejected file upload of size " + sizeMb +": not enough space!");
        return false;
    }

    return true;
}
 
Example 3
Project: RNLearn_Project1   File: ImageEditingManager.java   View Source Code Vote up 6 votes
/**
 * Create a temporary file in the cache directory on either internal or external storage,
 * whichever is available and has more free space.
 *
 * @param mimeType the MIME type of the file to create (image/*)
 */
private static File createTempFile(Context context, @Nullable String mimeType)
    throws IOException {
  File externalCacheDir = context.getExternalCacheDir();
  File internalCacheDir = context.getCacheDir();
  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(TEMP_FILE_PREFIX, getFileExtensionForType(mimeType), cacheDir);
}
 
Example 4
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 5
Project: Nird2   File: FilePlugin.java   View Source Code Vote up 6 votes
@Nullable
private TransportConnectionWriter createWriter(String filename) {
	if (!running) return null;
	File dir = chooseOutputDirectory();
	if (dir == null || !dir.exists() || !dir.isDirectory()) return null;
	File f = new File(dir, filename);
	try {
		long capacity = dir.getFreeSpace();
		if (capacity < MIN_STREAM_LENGTH) return null;
		OutputStream out = new FileOutputStream(f);
		return new FileTransportWriter(f, out, capacity, this);
	} catch (IOException e) {
		if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
		f.delete();
		return null;
	}
}
 
Example 6
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 7
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 8
Project: feeyo-redisproxy   File: Util.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 9
Project: iot-plat   File: ProxyBiz.java   View Source Code Vote up 6 votes
/**
 * 检查磁盘剩余空间
 */
private void checkDiskSpace(String path, int warningPercent) {
	try {
		nLastCheckDiskTime = System.currentTimeMillis();
		File f = new File(path);
		long n1 = f.getFreeSpace() / (1024 * 1024);
		long n2 = f.getTotalSpace() / (1024 * 1024);
		if (n2 == 0) n2 = 1;
		int nPercent = (int) (100 * n1 / n2);
		logger.info("“" + path + "”分区剩余磁盘空间:" + nPercent + "% [" + n1 + "m/" + n2 + "m]");
		if ("127.0.0.1".equals(mConfigMap.get("LOCAL_IP"))) {
			return;
		}
		if (nPercent < warningPercent) {
			String sContent = mConfigMap.get("LOCAL_IP") + "硬盘“" + path + "”分区可用空间低于"
					+ nPercent + "% [" + n1 + "m/" + n2 + "m],请服务器相关同学处理一下。(本邮件将在5分钟后再次发送)";
			EMail email = new EMail(
					new String[] { "[email protected]" },
					mConfigMap.get("LOCAL_IP") + "硬盘“" + path + "”分区可用空间低于" + nPercent
							+ "%", sContent);
			email.send();
		}
	} catch (Exception ex) {
		logger.error("", ex);
	}
}
 
Example 10
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 11
Project: hadoop-oss   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 12
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 13
Project: Nird2   File: H2Database.java   View Source Code Vote up 5 votes
@Override
public long getFreeSpace() throws DbException {
	File dir = config.getDatabaseDirectory();
	long maxSize = config.getMaxSize();
	long free = dir.getFreeSpace();
	long used = getDiskSpace(dir);
	long quota = maxSize - used;
	return Math.min(free, quota);
}
 
Example 14
Project: Nird2   File: H2Database.java   View Source Code Vote up 5 votes
@Override
public long getFreeSpace() throws DbException {
	File dir = config.getDatabaseDirectory();
	long maxSize = config.getMaxSize();
	long free = dir.getFreeSpace();
	long used = getDiskSpace(dir);
	long quota = maxSize - used;
	return Math.min(free, quota);
}
 
Example 15
Project: keycloak-health-checks   File: FilesystemHealthIndicator.java   View Source Code Vote up 5 votes
@Override
public HealthStatus check() {

  File path = new File(this.path);
  long freeBytes = path.getFreeSpace();
  long threshold = thresholdInBytes;

  boolean belowThreshold = freeBytes > threshold;

  return belowThreshold ? reportUp() : reportDown().withAttribute("freebytes", freeBytes);
}
 
Example 16
Project: ComponentProjectDemo   File: CommonUtils.java   View Source Code Vote up 5 votes
/**
 * 判断Sdcard是否存在
 *
 * @return
 */
public static boolean detectSdcardIsExist() {
    String extStorageState = Environment.getExternalStorageState();
    File file = Environment.getExternalStorageDirectory();
    if (!Environment.MEDIA_MOUNTED.equals(extStorageState)
            || !file.exists() || !file.canWrite()
            || file.getFreeSpace() <= 0) {
        return false;
    }
    return true;
}
 
Example 17
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 18
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 19
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 20
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;
    }
}