Computing the total, free and usable disk space easily using JDK 1.6

Note: This tool uses Jdk1.6. It does not work for lower versions of java sdk/jdk. You can run this tool to find the disk space, free space and usable disk space although for several of my test, usable space and free space returned the same value. This capability has been added to jdk1.6 version. Hence it will not work for any lower versions.

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * This tool use Jdk1.6. Does not work for lower versions.
 *
 * You can run this tool to find the disk space, free space and usable disk space
 * although for several of my test, usable space and free space returned the same
 * value. This capability has been added to jdk1.6 version. Hence it will not work
 * for lower versions.
 */
import java.io.File;

public class DiskSpaceJavaV6 {

	public static void main(String[] args) {
		File file = new File("c:");
		String unit="GB";
		DiskSpaceJavaV6 dspace=new DiskSpaceJavaV6();
		double totalDiskSpace = dspace.getTotalDiskSpace(file,unit );
		double usableSpace = dspace.getUsableSpace(file, unit);
		double freeSpace = dspace.getFreeSpace(file, unit);

		System.out.println("Total Disk Space: " +totalDiskSpace +" "+unit);
		System.out.println("Total Usable Space : " + usableSpace +" "+unit);
		System.out.println("Free Disk Space : " + freeSpace +" "+unit);
	}
	/**
	 * @param file - normally the top level drive e.g. c:
	 * @param unit - target unit for disk space. Allowed values KB, MB, GB.
	 * @return total disk space
	 */
	public double getTotalDiskSpace(File file, String unit) {
		return processUnit(file.getTotalSpace(), unit);
	}
	/**
	 * @param file - normally the top level drive e.g. c:
	 * @param unit - target unit for disk space. Allowed values KB, MB, GB.
	 * @return usable disk space
	 */
	public double getUsableSpace(File file, String unit) {
		return processUnit(file.getUsableSpace(), unit);
	}

	/**
	 * @param file - normally the top level drive e.g. c:
	 * @param unit - target unit for disk space. Allowed values KB, MB, GB.
	 * @return free space
	 */
	public double getFreeSpace(File file, String unit) {
		return processUnit(file.getFreeSpace(), unit);
	}

	/**
	 * @param space - disk space in bytes
	 * @param unit - the target unit. Allowed values: KB, MB, GB.
	 * @return processed value
	 */
	private double processUnit(long space, String unit) {
		String nonNullUnit=makeNonNullUnit(unit);
		if("KB".equalsIgnoreCase(nonNullUnit)) {
				return space/1024;
		} else if("MB".equalsIgnoreCase(nonNullUnit)) {
				return space/(1024*1024);
		} else if("GB".equalsIgnoreCase(nonNullUnit)) {
			return space/(1024*1024*1024);
		} else {
			return space;
		}
	}
	/**
	 * @param anyString
	 * @return non null value of the string
	 */
	private static String makeNonNullUnit(String anyString) {
		if(anyString==null) {
			return "";
		} else {
			return anyString;
		}
	}
}

Reading the Resource or Property files in Java as a file stream and outputting the content to console

A good programming practice is to avoid hardcoding values in your Java File. These values should be read from some resource files or proerty files. The major benefit of doing that is that in case you decide to alter those values, there is no need to recompile your classes. Another benefit is the isolation of the resources from the logic.

Is it difficult to read the resource from a file on to the Java class? No, it’s pretty simple. The following sample code that I wrote shows how easily you can read the content of your file as a stream. How you use the value thus read in your Java file is up to you. I have only demonstrated how the resource is actually read.

This program does the following:

  • Read resource file as a stream from Java class
  • Print the content of the resource file onto the Java console.

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * Created on 2012-07-03
 * Last Modified on 2012-07-03
 *
 * This class demonstrate how we can read the resource files as file input stream.
 * - Reads a resource file
 * - Prints file contests on to the console.
 */

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadResourceFile {

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

	private static void readResourceFileAndPrintContents() throws Exception {
		/** Get the input stream for the resource file**/
		InputStream stream = loadResourceAsStream ("C:/temp/myresources.properties");

		/**Create a BufferedReader object for the input stream**/
		BufferedReader in = new BufferedReader(new InputStreamReader(stream));

		/**Read the lines and print them onto the console**/
		String line;
	    while ((line = in.readLine()) != null) {
	        System.out.println((line));
	    }
	}

	/**
	 * This method
	 * - Takes a resource file name as parameter
	 * - Returns the InputStream object of FileInputStream type
	 */
	public static InputStream loadResourceAsStream(final String resourceName) {
		InputStream input = null;
		try {
			input = new FileInputStream(resourceName);
		} catch (FileNotFoundException e) {
			System.out.println("Resource File Not Found");
			e.printStackTrace();
		}
		return input;
	}

}

Content of the file c:/temp/myresources.properties

server=www.thisismyfantasticvirtualserver.com
port=1005
userid=mickeyrourke
password=dontcopymypasswordplease

Here is the output of this program, which is same as the content of the file. The java class simply read the resource file as stream and spit out the content onto the console.

server=www.thisismyfantasticvirtualserver.com
port=1005
userid=mickeyrourke
password=dontcopymypasswordplease

File Copy From Local Folder or Network Folder Using Java With Capability To Limit The Number

One of my network folders had more than 20000 files and every time I tried to open the foder by myself to copy some files, the windows would simply freeze or slow down to an extent that I could no longer operate on that folder. To get rid of the frustration and to be able to copy some of the files from that network drive to my local machine (I needed the files to do performance test on the attachments), I wrote this simple utility.

You can use this utility to copy files from one location to another.

  1. The source location can be over the network or another folder on your local machine.
  2. The destination fodler can also be another network location or simply another folder on your local machine.

You can also specify how many files you want to copy from the source location. For this you need to set the integer ‘numberOfFilesToCopy’ to the desired value.

Here is the code for the program.


package com.kushal.tools;

/**
 * @author Kushal Paudyal
 * Last Modified on: 2011-11-03
 * Utility to copy files from one folder to another.
 * - Can copy from Network location also.
 * - Can limit the total number of files to copy
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy {

	public static void main(String[] args) throws IOException {
		String fileLocationSourceNetwork = "\\mynetwork\mydata\";
		String fileLocationSourceDrive = "C:\mavenRepo";

		String fileLocationDestination = "C:\temp\";
		int numberOfFilesToCopy = 2;

		/**Copy the files from the network**/
		copyFiles(	fileLocationSourceNetwork,
					fileLocationDestination,
					numberOfFilesToCopy);

		System.out.println("nn");

		/**Copy the files from the drive**/
		copyFiles(	fileLocationSourceDrive,
				fileLocationDestination,
				numberOfFilesToCopy);

	}

	public static void copyFiles(String fileLocationSource,
			String fileLocationDestination, int numberOfFilesToCopy) {
		File inputLocation = new File(fileLocationSource);
		if (inputLocation.isDirectory()) {
			System.out.println("Listing the files...");
			File[] attachmentFiles = inputLocation.listFiles();
			System.out.println("Total files in the folder: "
					+ attachmentFiles.length);
			for (File aFile : attachmentFiles) {
				if (!aFile.isDirectory()) {
					String fileName = aFile.getName();
					String sourceFileName = aFile.getAbsolutePath();
					String destinationFileName = fileLocationDestination
							+ fileName;
					copyFile(sourceFileName, destinationFileName);
				}
				if (numberOfFilesToCopy >= 0) {
					if (--numberOfFilesToCopy == 0) {
						break;
					}
				}
			}
		}
		System.out.println("Completed...");
	}

	/**
	 *
	 * @param sourceFileName
	 * @param destionFileName
	 *
	 *            Copies a single file from source location to a destination
	 *            location.
	 */
	private static void copyFile(String sourceFileName, String destionFileName) {
		try {
			System.out.println("Reading..." + sourceFileName);
			File sourceFile = new File(sourceFileName);
			File destinationFile = new File(destionFileName);
			InputStream in = new FileInputStream(sourceFile);
			OutputStream out = new FileOutputStream(destinationFile);

			byte[] buffer = new byte[1024];
			int length;
			while ((length = in.read(buffer)) > 0) {
				out.write(buffer, 0, length);
			}
			in.close();
			out.close();
			System.out.println("Copied: " + sourceFileName);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

The following is the output of this program:

Listing the files...
Total files in the folder: 23632
Reading...\mynetworkmydatainput_1045863400149541657_010106687.txt
Copied: \mynetworkmydatainput_1045863400149541657_010106687.txt
Reading...\mynetworkmydatainput_1045863400149541657_010107578.txt
Copied: \mynetworkmydatainput_1045863400149541657_010107578.txt
Completed...



Listing the files...
Total files in the folder: 16
Reading...C:mavenRepocom.ibm.mqjms.jar
Copied: C:mavenRepocom.ibm.mqjms.jar
Reading...C:mavenRepodb2jcc.jar
Copied: C:mavenRepodb2jcc.jar
Completed...