Showing posts with label file IO. Show all posts
Showing posts with label file IO. Show all posts

Wednesday, 11 May 2011

Write byte array to file using BufferedOutputStream

Writing the function:

public static void writeByteArrayToFile(String fileName, byte[] byteArr)
{
BufferedOutputStream bos = null;
try
{
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(strFileName));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);


/*
* To write byte array to file use,
* public void write(byte[] b) method of BufferedOutputStream
* class.
*/
System.out.println("Writing byte array to file");
bos.write(byteArr);
System.out.println("File written");
}
catch(FileNotFoundException fnfe)
{
System.out.println("Specified file not found" + fnfe);
}
catch(IOException ioe)
{
System.out.println("Error while writing file" + ioe);
}
finally
{
if(bos != null){
try
{
//flush the BufferedOutputStream
bos.flush();
//close the BufferedOutputStream
bos.close();
}
catch(Exception e){//don't swallow
//exceptions..add your code accordingly
}
}
}
}


Using the above function:


String fileName = "C:\demo.txt";
String str = "BufferedOutputStream Example to write byte array";
writeByteArrayToFile(fileName,str.getBytes());

Friday, 15 April 2011

Files-Directory listing in Java

This example lists the files and subdirectories in a directory.
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i < children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}

// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);

// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();

// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);

Traversing the Files and Directories Under a Directory
This example implements methods that recursively visits all files and directories under a directory.
// Process all files and directories under dir
public static void visitAllDirsAndFiles(File dir) {
process(dir);

if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}

// Process only directories under dir
public static void visitAllDirs(File dir) {
if (dir.isDirectory()) {
process(dir);

String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllDirs(new File(dir, children[i]));
}
}
}

// Process only files under dir
public static void visitAllFiles(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllFiles(new File(dir, children[i]));
}
} else {
process(dir);
}
}


Monday, 11 April 2011

Calculate Free Disk Space in Java using Apache Commons IO

As a Java developer, lot of times I have to play around with file system. Sometimes I have to copy files/directories from one location to another; sometimes have to process certain files depending on certain pattern. In one of my test program, I wanted to calculate available disk space using Java. Lot of code snippets are available for this task. I liked the one using Apache Commons IO library.
Here is a simple trick for Java developers to calculate free diskspace. We have used Apache Commons IO library to calculate this.
Apache Commons IO library contains a class org.apache.commons.io.FileSystemUtils which can be used to calculate the free disk space in any system. Let us see the Java code for this.

 
import java.io.IOException;
 
import org.apache.commons.io.FileSystemUtils;
 
public class DiskSpace {
    public static void main(String[] args) {
        try {
 
            //calculate free disk space
            double freeDiskSpace = FileSystemUtils.freeSpaceKb("C:");
 
            //convert the number into gigabyte
            double freeDiskSpaceGB = freeDiskSpace / 1024 / 1024;
 
            System.out.println("Free Disk Space (GB):" + freeDiskSpaceGB);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Output:
Free Disk Space (GB): 40.145268
In above code we used FileSystemUtils.freeSpaceKb( ) method to get the free space in kilo byte. This method invokes the command line to calculate the free disk space. You may want to call this method in following way to get free disk space in Windows and Linux.

FileSystemUtils.freeSpaceKb("C:");       // Windows
FileSystemUtils.freeSpaceKb("/volume");  // *nix
The free space is calculated via the command line. It uses ‘dir /-c’ on Windows, ‘df -kP’ on AIX/HP-UX and ‘df -k’ on other Unix.
In order to work, you must be running Windows, or have a implementation of Unix df that supports GNU format when passed -k (or -kP). If you are going to rely on this code, please check that it works on your OS by running some simple tests to compare the command line with the output from this class.