Java如何获得硬盘剩余空间

Java如何获得硬盘剩余空间,第1张

java中可以使用file对象,获取当前电脑硬盘基本信息,示例如下:

import javaioFile;

 

public class DiskSpaceDetail {

 

    public static void main(String[] args) {

 

        File diskPartition = new File("C:");

 

        long totalCapacity = diskPartitiongetTotalSpace(); 

 

        long freePartitionSpace = diskPartitiongetFreeSpace(); 

        long usablePatitionSpace = diskPartitiongetUsableSpace(); 

 

        Systemoutprintln(" Sizes in Mega Bytes \n");

 

        Systemoutprintln("Total C partition size : " + totalCapacity / (10241024) + " MB");

        Systemoutprintln("Usable Space : " + usablePatitionSpace / (1024 1024) + " MB");

        Systemoutprintln("Free Space : " + freePartitionSpace / (1024 1024) + " MB");

 

        Systemoutprintln("\n Sizes in Giga Bytes \n");

 

        Systemoutprintln("Total C partition size : " + totalCapacity / (102410241024) + " GB");

        Systemoutprintln("Usable Space : " + usablePatitionSpace / (1024 10241024) + " GB");

        Systemoutprintln("Free Space : " + freePartitionSpace / (1024 10241024) + " GB");

    }

}

File dir = new File("e:\\");

File[] files = dirlistFiles();

for(File file : files)

Systemoutprintln(filegetAbsolutePath());

这样试一下哈。。。。我试过了。。。应该是可以的。。

你自己试下哈。。。希望能帮到你。。。

1、在远程server里搭建一个>

一般来讲 要用java得到硬盘空间 有 种方法: 调用system的mand 然后分析得到的结果 这种方法有很强的系统依赖性 linux下和win下要分别写程序下面是一个win下的例子 编译成功之后 运行java Diskspace yourdir(比如c:\)import java io BufferedReader;import java io InputStreamReader;/ Determine free disk space for a given directory by parsing the output of the dir mand This class is inspired by the code at Works only under Windows under certain circumstances Yes it s that shaky Requires Java or higher @[EMAIL PROTECTED]Marco Schmidt/public class Diskspace{private Diskspace(){// prevent instantiation of this class}/ Return available free disk space for a directory @[EMAIL PROTECTED]dirName name of the directory @[EMAIL PROTECTED]free disk space in bytes or if unknown/public static long getFreeDiskSpace(String dirName){try{// guess correct dir mand by looking at the// operating system nameString os = System getProperty( os name );String mand;if (os equals( Windows NT ) ||os equals( Windows )){mand = cmd exe /c dir + dirName;}else{mand = /c dir + dirName;}// run the dir mand on the argument directory nameRuntime runtime = Runtime getRuntime();Process process = null;process = runtime exec(mand);if (process == null){return ;}// read the output of the dir mand// only the last line is of interestBufferedReader in = new BufferedReader(new InputStreamReader(process getInputStream()));String line;String freeSpace = null;while ((line = in readLine()) != null){freeSpace = line;}if (freeSpace == null){return ;}process destroy();// remove dots & mas & leading and trailing whitespacefreeSpace = freeSpace trim();freeSpace = freeSpace replaceAll( \\ );freeSpace = freeSpace replaceAll( );String[] items = freeSpace split( );// the first valid numeric value in items after(!) index // is probably the free disk spaceint index = ;while (index < itemslength){try{long bytes = LongparseLong(items[index++]);return bytes;}catch (NumberFormatException nfe){}}return -1;}catch (Exception exception){return -1;}}/ Command line program to print the free diskspace to stdout for all 26 potential root directories A:\ to Z: (when no parameters are given to this program) or for those directories (drives) specified as parameters @[EMAIL PROTECTED]args program parameters/public static void main(String[] args){if (argslength == 0){for (char c = 'A'; c <= 'Z'; c++){String dirName = c + ":\\";Systemoutprintln(dirName + " " +getFreeDiskSpace(dirName));}}else{for (int i = 0; i < argslength; i++){Systemoutprintln(args[i] + " " +getFreeDiskSpace(args[i]));}}}} 方法二:使用Jconfig,可以跨平台 从上下载jconfig下载的包的sample里有很简单的例子,如果是要得到磁盘空间的话:用FileRegistrygetVolumes()得到DiskVolume然后call getFreeSpace()和getMaxCapacity()就是这么简单:) 方法三:jni 这个是解决所有和os相关的 *** 作的万能利器了例子我也懒得写了写一个dll然后call之即可 lishixinzhi/Article/program/Java/Javascript/201311/25405

啥也不说了直接看代码

import java lang management ManagementFactory;

import sun management OperatingSystemMXBean;

public class Test {

public static void main(String[] args) {

OperatingSystemMXBean o b = (OperatingSystemMXBean) ManagementFactory getOperatingSystemMXBean();

System out println( 系统物理内存总计 + o b getTotalPhysicalMemorySize() / / + MB );

System out println( 系统物理可用内存总计 + o b getFreePhysicalMemorySize() / / + MB );

}

}

ManagementFactory getOperatingSystemMXBean()返回的是java lang management里面的OperatingSystemMXBean

我们要用的是 sun management OperatingSystemMXBean;

在java类库中可以查到

public abstract Interface sun management OperatingSystemMXBean extends java lang management OperatingSystemMXBean

所以我们可以强制转换一下

jdk 下的磁盘使用情况例子:

import java io File;

/

jdk 下的磁盘使用情况例子

/

public class Diskfree {

public static void main(String[] args) {

File[] roots = File listRoots();//获取磁盘分区列表

for (File file : roots) {

System out println(file getPath() + 信息如下: );

System out println( 空闲未使用 = + file getFreeSpace() / / / + G );//空闲空间

System out println( 已经使用 = + file getUsableSpace() / / / + G );//可用空间

System out println( 总容量 = + file getTotalSpace() / / / + G );//总空间

System out println();

}

}

lishixinzhi/Article/program/Java/hx/201311/26599

package comcmmbutil;

import javaio;

/

linux 下cpu 内存 磁盘 jvm的使用监控

@author avery_leo

/

public class DiskSpace {

/

获取cpu使用情况

@return

@throws Exception

/

public double getcpuUsage() throws Exception {

double cpuUsed = 0;

Runtime rt = RuntimegetRuntime();

Process p = rtexec("top -b -n 1");// 调用系统的“top"命令

BufferedReader in = null;

try {

in = new BufferedReader(new InputStreamReader(pgetInputStream()));

String str = null;

String[] strArray = null;

while ((str = inreadLine()) != null) {

int m = 0;

if (strindexOf(" R ") != -1) {// 只分析正在运行的进程,top进程本身除外 &&

strArray = strsplit(" ");

for (String tmp : strArray) {

if (tmptrim()length() == 0)

continue;

if (++m == 9) {// 第9列为cpu的使用百分比(RedHat

cpuUsed += DoubleparseDouble(tmp);

}

}

}

}

} catch (Exception e) {

eprintStackTrace();

} finally {

inclose();

}

return cpuUsed;

}

/

内存监控

@return

@throws Exception

/

public double getMemUsage() throws Exception {

double menUsed = 0;

Runtime rt = RuntimegetRuntime();

Process p = rtexec("top -b -n 1");// 调用系统的“top"命令

BufferedReader in = null;

try {

in = new BufferedReader(new InputStreamReader(pgetInputStream()));

String str = null;

String[] strArray = null;

while ((str = inreadLine()) != null) {

int m = 0;

if (strindexOf(" R ") != -1) {// 只分析正在运行的进程,top进程本身除外 &&

//

// Systemoutprintln("------------------3-----------------");

strArray = strsplit(" ");

for (String tmp : strArray) {

if (tmptrim()length() == 0)

continue;

if (++m == 10) {

// 9)--第10列为mem的使用百分比(RedHat 9)

menUsed += DoubleparseDouble(tmp);

}

}

}

}

} catch (Exception e) {

eprintStackTrace();

} finally {

inclose();

}

return menUsed;

}

/

获取磁盘空间大小

@return

@throws Exception

/

public double getDeskUsage() throws Exception {

double totalhd = 0;

double usedhd = 0;

Runtime rt = RuntimegetRuntime();

Process p = rtexec("df -hl /home");//df -hl 查看硬盘空间

BufferedReader in = null;

try {

in = new BufferedReader(new InputStreamReader(pgetInputStream()));

String str = null;

String[] strArray = null;

while ((str = inreadLine()) != null) {

int m = 0;

strArray = strsplit(" ");

for (String tmp : strArray) {

if (tmptrim()length() == 0)

continue;

++m;

Systemoutprintln("----tmp----" + tmp);

if (tmpindexOf("G") != -1) {

if (m == 2) {

Systemoutprintln("---G----" + tmp);

if (!tmpequals("") && !tmpequals("0"))

totalhd += DoubleparseDouble(tmp

substring(0, tmplength() - 1)) 1024;

}

if (m == 3) {

Systemoutprintln("---G----" + tmp);

if (!tmpequals("none") && !tmpequals("0"))

usedhd += DoubleparseDouble(tmpsubstring(

0, tmplength() - 1)) 1024;

}

}

if (tmpindexOf("M") != -1) {

if (m == 2) {

Systemoutprintln("---M---" + tmp);

if (!tmpequals("") && !tmpequals("0"))

totalhd += DoubleparseDouble(tmp

substring(0, tmplength() - 1));

}

if (m == 3) {

Systemoutprintln("---M---" + tmp);

if (!tmpequals("none") && !tmpequals("0"))

usedhd += DoubleparseDouble(tmpsubstring(

0, tmplength() - 1));

Systemoutprintln("----3----" + usedhd);

}

}

}

}

} catch (Exception e) {

eprintStackTrace();

} finally {

inclose();

}

//上面写在userd和total写反了,懒得改了,就反着用了

Systemoutprintln("----totalhd----" + usedhd);

Systemoutprintln("----usedhd----" + totalhd);

return (totalhd / usedhd) 100;

}

public static void main(String[] args) throws Exception {

DiskSpace cpu = new DiskSpace();

Systemoutprintln("---------------cpu used:" + cpugetcpuUsage() + "%");

Systemoutprintln("---------------mem used:" + cpugetMemUsage() + "%");

Systemoutprintln("---------------HD used:" + cpugetDeskUsage() + "%");

Systemoutprintln("------------jvm监控----------------------");

Runtime lRuntime = RuntimegetRuntime();

Systemoutprintln("--------------Free Momery:" + lRuntimefreeMemory()+"K");

Systemoutprintln("--------------Max Momery:" + lRuntimemaxMemory()+"K");

Systemoutprintln("--------------Total Momery:" + lRuntimetotalMemory()+"K");

Systemoutprintln("---------------Available Processors :"

+ lRuntimeavailableProcessors());

}

}

以上就是关于Java如何获得硬盘剩余空间全部的内容,包括:Java如何获得硬盘剩余空间、java为什么不能获取盘符下的文件列表。。我把“e:”作为一个dir。。用file.list()方法、java如何获取远程计算机的系统信息,cpu使用情况,磁盘使用情况等等等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9768643.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-01
下一篇 2023-05-01

发表评论

登录后才能评论

评论列表(0条)

保存