Use Java to view disk space size

xiaoxiao2021-03-06  53

Below is an example of WIN, after compiling, run Java DiskSpace youRDir (such as C: /)

import java.io.BufferedReader; import java.io.InputStreamReader;. / *** Determine free disk space for a given directory by * parsing the output of the dir command * This class is inspired by the code at * Works only under Windows under certain circumstances. * Yes, it's that shaky. * Requires Java 1.4 or higher. * @ [EMAIL PROTECTED] * Marco Schmidt * / public class Diskspace {private Diskspace () {// prevent instantiation of this class}

/ *** RETURN AVAILALALALE DISK SPACE for A Directory. * @ [Email protected] DIRNAME NAME OF THE DIRECTORY * @ [email protected] free disk space in bytes or -1 if unknown * /

public static long getFreeDiskSpace (String dirName) {try {// guess correct 'dir' command by looking at the // operating system name String os = System.getProperty ( "os.name"); String command; if (os.equals ("Windows NT") || Os.Equals ("Windows 2000")) {Command = "cmd.exe / C Dir" DirName;} else {command = "Command.com / C Dir" DirName;} / / run the dir command on the argument directory name Runtime runtime = Runtime.getRuntime (); Process process = null; process = runtime.exec (command); if (process == null) {return -1;} // read the output of the dir command // only the last line is of interest BufferedReader in = new BufferedReader (new InputStreamReader (process.getInputStream ())); String line; String freeSpace = null; while ((line = in.readLine ()) ! = null) {free (free == null) {return -1;} process.destroy ();

// Remove dots & comMAS & Leading and trailing whitespace free = free.trim (); FreeSpace = free.replacell ("//.", ""); freespace = free .replaceAll (",", ","); String [] iTems = free.split (""); // the first valid numeric value in items after (!) Index 0 // is probably the free disk space int index = 1; while (index

Method 2: Using JCONFIG, you can cross the platform

Download JCONFIG from http://www.tolstoy.com/samizdat/jconfig.html.

There is a simple example in the sample of the download package, if you want to get the disk space:

Use FileRegistry.getvolumes () to get DiskVolume.

Then Call getFreespace () and getmaxcapacity ().

It is so simple.

Method 3: JNI

This is a universal utilizer that solves all and OS-related operations.

I was too lazy to write.

Write a DLL and then Call.

转载请注明原文地址:https://www.9cbs.com/read-117894.html

New Post(0)