Java Tutorials
Building Hadoop MapReduce Jobs In Java
Building XML With Java And DOM
Creating Java Servlets With NetBeans
Basic File Manipulation With Java
Introduction To Java

Basic File Manipulation With Java

Using the RandomAccessFile Package

The RandomAccessFile package supports both read and write file operations. Works as an array of bytes with a file pointer aimed at the current position in the array. When writing the write starts at the current position of the file pointer and will extend the length of the array if necessary.

Create RandomEx1.java

import java.io.RandomAccessFile;
import java.io.File;
import java.io.IOException;
class RandomEx1 {
    public static void main(String args[]) {
        if (args.length != 1) {
            System.out.println("Please specify a file on the command line");
            return;
        }
        try {
            File f = new File(args[0]);
            RandomAccessFile file = new RandomAccessFile(f, "rw");
            System.out.println("The length of " + f.getName() + " is " + file.length());
            System.out.println("First line: " + file.readLine());
            System.out.println("The First character of the second line: " + (char)file.readByte());
            file.seek(file.length());
            file.writeChar('n');
            file.writeChars("This is appended to the endn");
            file.close();
        } catch(IOException e) {
            System.out.println("Input/output error");
        }
    }
}

First verify the file to work with was specified on the command line. Create a new File object from the input file. Then open the file with RandomAccessFile in read/write mode. Then print the length of the file, the first line of the file, and the first character of the second line. Next seek to the end of the file, append a new line, and then add a new text line.

Create RandomEx2.java

import java.io.RandomAccessFile;
import java.io.File;
import java.io.IOException;
class RandomEx2 {
    public static void main(String args[]) {
        int buflen = 1024;
        String bufString = null;
        if (args.length != 1) {
            System.out.println("Please specify a file on the command line");
            return;
        }
        try {
            RandomAccessFile file = new RandomAccessFile(args[0], "rw");
            if (file.length()  < buflen) {
                buflen = (int)file.length();
            }
            byte[] buf = new byte[buflen];
            file.readFully(buf);
            bufString = new String(buf);
            System.out.println("The first " + buflen + " bytes of file: " + bufString);
            file.seek(10);
            file.writeBytes("Test");
        } catch(IOException e) {
            System.out.println("Input/output error" + e.toString());
        }
    }
}

Create an integer buflen with a value of 1024, that will be used to initialize a byte array. Next create a string that will be used to print the byte array. Open the input file in read/write mode. Notice this time no File object is created the filename is passed directly. If the file is smaller than the set buflen reset the buflen to the file length. This will prevent an exception for reading past the end of file. Initialize the byte array. Then read the buffer, and print the buffer. Finally seek back to the tenth byte in the file and write "test".

File locking

When multiple applications or multiple instances of an application need read/write access to a file proper file locking is a must. Proper file locking will prevent incomplete reads and/or conflicting writes. Filesystem based locks can't always be trusted, especially on network filesystems. File locking mechanisms are as simple as creating a file to manage the lock, it can optionally contain the process ID, the user or comment as to the purpose of the lock, or any other pertinent information.

Create a directory Lock and put the file FileLock.java inside

package Lock;
import java.io.*;

public class FileLock {
    private String fileName;
    private File file;
    public FileLock(String fileName) {
        this.fileName = fileName;
        this.file = new File(fileName + ".LOCK");
    }

    public boolean getLock() {
        if (!this.isLocked()) {
            return(this.setLock());
        }
        return(false);
    }

    public boolean getLock(int tries, int seconds) throws InterruptedException {
        boolean locked = false;
        for (int i=0; i < tries; i++) {
            locked = this.getLock();
            if (locked) {
                return(true);
            }
            Thread.sleep(seconds * 1000);
        }
        return(false);
    }

    public void releaseLock() {
        file.delete();
    } 
    
    public boolean isLocked() {
        return(file.exists());
    }

    private boolean setLock() {
        try {
            return(file.createNewFile());
        } catch (Exception e) {
            return(false);
        }
    }
}

Initialize 2 private class variables, one stores the file name of the file we're managing the lock on. The other is a File object for the lock file. The constructor expects a string with the path to a file to manage locking on. The method getLock() simply checks if the lock file exists and if the lock is available sets the lock file. Next overload the getLock method to accept a number of tries to get the lock and the amount of time to sleep between each attempt. This function simply attempts to get the lock and if it can't sleeps a specified number of seconds before trying again up to a specified number of iterations.

Once we're done with the lock we need to release the lock for others so we have the releaseLock() method delete the lock file. The method isLocked() simply checks for the existence of a lock file. Finally we have the setLock() private method to actually create the lock file.

Go back to the parent directory and create FileLockDemo.java

import java.io.*;
import Lock.*;

class FileLockDemo {
    public static void main(String args[]) throws InterruptedException {
        FileLock lock = new FileLock(args[0]);
        lock.getLock(10, 30);
        lock.releaseLock();
    }
}

This simple example creates a new instance of FileLock and tries to get a lock and will try 10 times sleeping for 30 seconds between tries. Once it has the lock it simply releases it and exits.

Basics, Reading, and Writing Files <<  1 2
New Content

Related Information
Introduction To Java