67,512
社区成员
发帖
与我相关
我的任务
分享
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Diskspace {
public Diskspace() {
}
public static long getFreeDiskSpace(String dirName) {
try {
String os = System.getProperty("os.name");
String command;
if (os.equals("Windows NT") || os.equals("Windows 2000")
|| os.equals("Windows XP")) {
command = "cmd.exe /c dir " + dirName;
} else {
command = "command.com /c dir " + dirName;
}
Runtime runtime = Runtime.getRuntime();
Process process = null;
process = runtime.exec(command);
if (process == null) {
return -1;
}
BufferedReader in = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line;
String freeSpace = null;
while ((line = in.readLine()) != null) {
freeSpace = line;
}
if (freeSpace == null) {
return -1;
}
process.destroy();
freeSpace = freeSpace.trim();
freeSpace = freeSpace.replaceAll("\\.", "");
freeSpace = freeSpace.replaceAll(",", "");
String[] items = freeSpace.split(" ");
int index = 1;
while (index < items.length) {
try {
long bytes = Long.parseLong(items[index++]);
return bytes;
} catch (NumberFormatException nfe) {
}
}
return -1;
} catch (Exception ex) {
return -1;
}
}
public static void main(String[] args) {
long l = 0;
if (args.length == 0) {
char[] c = { 'C', 'D', 'E', 'F' };
for (int i = 0; i < c.length; i++) {
String dirName = c[i] + ":\\";
System.out.println(dirName + " " + getFreeDiskSpace(dirName));
l += getFreeDiskSpace(dirName);
}
} else {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i] + " " + getFreeDiskSpace(args[i]));
}
}
}
}
/* Total number of processors or cores available to the JVM */
System.out.println("Available processors (cores): "
+ Runtime.getRuntime().availableProcessors());
/* Total amount of free memory available to the JVM */
System.out.println("Free memory (bytes): "
+ Runtime.getRuntime().freeMemory());
/* This will return Long.MAX_VALUE if there is no preset limit */
long maxMemory = Runtime.getRuntime().maxMemory();
/* Maximum amount of memory the JVM will attempt to use */
System.out.println("Maximum memory (bytes): "
+ (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));
/* Total memory currently in use by the JVM */
System.out.println("Total memory (bytes): "
+ Runtime.getRuntime().totalMemory());
/* Get a list of all filesystem roots on this system */
File[] roots = File.listRoots();
/* For each filesystem root, print some info */
for (File root : roots) {
// 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());
}