Showing posts with label Files and Streams. Show all posts
Showing posts with label Files and Streams. Show all posts

20.3.RandomAccessFile

Sunday, April 18, 2010 Posted by Sudarsan 1 comments
In this post, first we need to look at the Class hierarchy of Input and OutputStreams in java.io.

Just see the fallowing diagram to understand the Class hierarchy.


RandomAccessFile

RandomAccessFile is used for files containing records of known size so that you can move from one record to another using seek( ), then read or change the records. The records don’t have to be the same size; you just have to be able to determine how big they are and where they are placed in the file.

At first it’s a little bit hard to believe that RandomAccessFile is not part of the InputStream or OutputStream hierarchy. It has no association with those hierarchies other than that it happens to implement the DataInput and DataOutput interfaces (which are also implemented by DataInputStream and DataOutputStream).

It doesn’t even use any of the functionality of the existing InputStream or OutputStream classes – it’s a completely separate class, written from scratch, with all of its own (mostly native) methods. The reason for this may be that RandomAccessFile has essentially different behavior than the other IO types, since you can move forward and backward within a file.

Essentially, a RandomAccessFile works like a DataInputStream pasted together with a DataOutputStream and the methods getFilePointer( ) to find out where you are in the file, seek( ) to move to a new point in the file, and length( ) to determine the maximum size ofthe file.

In addition, the constructors require a second argument (identical to fopen( ) in C)indicating whether you are just randomly reading (“r”) or reading and writing (“rw”).

There’s no support for write-only files, which could suggest that RandomAccessFile might have worked well if it were inherited from DataInputStream.

The seeking methods are available only in RandomAccessFile, which works for files only.

Let’s have a look at how the RandomAccessFile will work by the help of an example.

// Read/write to a Random Access file

package randomaccess;

import java.io.RandomAccessFile;

/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception{
        // TODO code application logic here
        
        RandomAccessFile ras = new RandomAccessFile("ras.txt","rw");

       // We can also pass File & fileDescriptor objects to fis.

        byte b[] = {1,2,3,4,5,65,6,3,33,52,32,2,33,4}; //photo

        writeRecord(ras,"x",100,10000f,b);
        System.out.println("Record pointer is at :" + ras.getFilePointer());
        writeRecord(ras,"y",101,10000f,b);
        System.out.println("Record pointer is at :" + ras.getFilePointer());

        writeRecord(ras,"a",102,10000f,b);
        writeRecord(ras,"b",103,10000f,b);
        writeRecord(ras,"c",104,10000f,b);

        printRecords(ras,1);
        printRecords(ras,2);
        printRecords(ras,20);
        ras.close();
    }
    
    private static void writeRecord(RandomAccessFile r, String name, int eno,float sal, byte photo[]) throws Exception
    {
        r.writeUTF(name);
        r.writeInt(eno);
        r.writeFloat(sal);
        r.writeUTF(photo,0,photo.length);
        r.writeUTF("\n");
    }
    
    private static void printrecords(RandomAccessFile r, int recno) throws Exception
    {
        long curpos = r.getFilepointer();
        
        //set the file pointer to appropriate position
        long newpos = (recno-1)*30;
        r.seek(newpos);
        System.out.println("r.readUTF() + " ");
        System.out.println("r.readInt() + " ");
        System.out.println("r.readFloat() + " ");

        //System.out.println(ras.readBytes(phto,0,photo.length);
        //ras.writeString("\n");

        r.seek(curpos);
    }

}

That's all for this time folks !, we will meet once again with some interesting topics.

20.2.Serialization

Saturday, April 17, 2010 Posted by Sudarsan 0 comments
Serialization

The Java Virtual Machine (JVM) supports the ability to read or write an object to a stream. This capability is called serialization, the process of "flattening" an object so that it can be saved to some permanent storage or passed to another object via the OutputStream class.

When writing an object , it is important that its state be written in a serialized form such that the object can be reconstructed as it is being read. Saving an object to some type of permanent storage is known as persistence.

The streams used for deserializing and serializing are the ObjectInputSt ream and theObjectOutputStream classes, respectively.

To allow an object to be serializable ( i.e., can be saved and retrieved) , its class should implement the Serializable interface.

The class should also provide a default constructor or a constructor with no arguments. One nice thing about serializability is that it is inherited, which means that we don’t have to implement Serializable on every class.

This means less work for programmers. You can just implement Serializable once along the class heirarchy.

The transient Keyword

When an object is serialized, only the object ’s data are preserved. Methods and constructors are not part of the serialized stream. There are some objects though that are not serializable because the data they represent constantly changes.

Some examples of such objects are FileInputStream and Thread objects. A NotSerializableException is thrown if the serialization operation fails for some reason.

A class containing a non-serializable object can still be serialized, if the reference to this non- serializable object is marked with the transient keyword.

Consider the following example:

class MyClass implements Serializable {
transient Thread thread; //try removing transient
int data;
/* some other data */
}

The transient keyword prevents the data from being serialized. Instantiating objects from this class can now be written to an OutputSt ream.

Serialization: Writing an Object Stream

To write an object to a stream, you need to use the ObjectOutputStream class and its writeObject method.

The writeObject method has the following signature:

public final void writeObject(Object obj) throws IOException

where obj is the object to be written to the stream.

The example below writes a Boolean object to an ObjectOutputStream.

The Boolean class implements the Serializable interface. Thus, objects instantiated from this class can be written to and read from a stream.

//ObjectOutputStream Example

package serialization;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 *
 * @author Administrator
 */


        
public class Main {

    /**
     * @param args the command line arguments
     */
    
    Main()
    {
        Boolean booleanData = new Boolean("true");
    
    try
    {
        FileOutputStream fos = new
        FileOutputStream("boolean.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        oos.writeObject(booleanData);
        oos.close();
    }
    catch (IOException ie)
    {
        ie.printStackTrace();
    }   
    }
       
    public static void main(String[] args) {
        // TODO code application logic here
        
        Main ob = new Main();
    }

}


When you compile this program boolen.ser file will be formed in your local directory.

Deserialization: Reading an Object St ream

To read an object from a stream, you need to use the ObjectInputStream class and its
readObject method. The readObject method has the following signature:

public final Object readObject()throws IOException, ClassNotFoundException


where obj is the object to be read from the stream. The Object type returned should be typecasted to the appropriate class name before methods on that class can be executed.

The example below reads a Boolean object from an
ObjectInputStream. This is a continuation of the previous example on serialization.

//ObjectInputStream Example

package serialization;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 *
 * @author Administrator
 */


        
public class Main {

    /**
     * @param args the command line arguments
     */
    
    Main()
    {
        Boolean booleanData = null;
        
        try
        {
            FileInputStream fis = new FileInputStream("boolean.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);

            booleanData = (Boolean) ois.readObject();
            ois.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        System.out.println("Unserialized Boolean from " + "boolean.ser");
        System.out.println("Boolean data: " + booleanData);
        System.out.println("Compare data with true: " +

        booleanData.equals(new Boolean("true")));
    }
       
    public static void main(String[] args) {
        // TODO code application logic here
        
        Main ob = new Main();
    }

}

20.1. File Methods

Friday, April 16, 2010 Posted by Sudarsan 0 comments
In order to use more methods of File class just go to java.io package in Java API.

File Methods

The File class provides several methods for manipulating files and directories. Here are some of these methods.

public String getName()
//Returns the filename or the directory name of this File object .
public boolean exists()
//Tests if a file or a directory exists.
public long length()
//Returns the size of the file.
public long lastModified()
//Returns the date in milliseconds when the file was last modified.
public boolean canRead()
//Returns t rue if it ’s permissible to read from the file. Otherwise, it returns false.
public boolean canWrite()
//Returns t rue if it ’s permissible to write to the file. Otherwise, it returns false.
public boolean isFile()
//Tests if this object is a file, that is, our normal percept ion of what a file is (not a directory) .
public boolean isDirectory()
//Tests if this object is a directory.
public String[] list()
//Returns the list of files and subdirectories within this object . This object should be a directory.
public void mkdir()
//Creates a directory denoted by this abst ract pathname.
public void delete()
//Removes the actual file or directory represented by this File object .


Let ’s see how these methods work by trying out the following example:

package files1;

// File Class Methods Demo

import java.io.File;


/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        //Input any file at command line
        
        String fileName = "C:\\Program Files\\NetBeans 6.1\\LICENSE.txt";
        File fn = new File(fileName);
        
        System.out.println("Name: " + fn.getName());
        if (!fn.exists())
        {
            System.out.println(fileName + " does not exists.");
            
            /* Create a temporary directory instead. */
            
            System.out.println("Creating temp directory...");
            fileName = "temp";
            fn = new File(fileName);
            fn.mkdir();

            System.out.println(fileName +(fn.exists()? "exists": "does not exist"));
            System.out.println("Deleting temp directory...");
            fn.delete();
            
            System.out.println(fileName +(fn.exists()? "exists": "does not exist"));
            return;
        }

        System.out.println(fileName + " is a " +(fn.isFile()? "file." :"directory."));

        if (fn.isDirectory())
        {
                String content[] = fn.list();
                System.out.println("The content of this directory:");
                
                for (int i = 0; i < content.length; i++)
                {
                    System.out.println(content[i]);
                }
        }
        
        if (!fn.canRead())
        {
            System.out.println(fileName + " is not readable.");
            return;
        }

        System.out.println(fileName + " is " + fn.length() +" bytes long.");
        System.out.println(fileName + " is " + fn.lastModified()+ " bytes long.");

        if (!fn.canWrite())
        {
            System.out.println(fileName + " is not writable.");
        }
    }
        
    }

When we compile this program we can get the fallowing output Name: LICENSE.txt C:\Program Files\NetBeans 6.1\LICENSE.txt is a file. C:\Program Files\NetBeans 6.1\LICENSE.txt is 77141 bytes long. C:\Program Files\NetBeans 6.1\LICENSE.txt is 1212117964000 bytes long. Sequential-Access Text Files In this section, we create and manipulate sequential access files. These files are in which records are stored in order by the record-key filed. Creating Sequential File In order to store data in a file first we need to create a class, let us assume the fallowing class.
// A class that represents one record of Information

package seqfiles;

/**
 *
 * @author Administrator
 */
public class AccountRecord {
    
    private int account;
    private String firstname;
    private String lastname;
    private double balance;
    
    public AccountRecord()
    {
        this(0,"","",0.0);
    }
    
    public AccountRecord(int acct,String first,String last,double bal)
    {
        setAccount(acct);
        setFirstname(first);
        setLastname(last);
        setBalance(bal);
    }

    public int getAccount() {
        return account;
    }

    public void setAccount(int account) {
        this.account = account;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

}
After this we need to implement Formatter class to write data into the file.
//Writing data to a text file with class Formatter
package seqfiles;

import java.util.Formatter;
import java.util.Scanner;

/**
 *
 * @author Administrator
 */
public class CreateTextFile {
    
    private Formatter output;
    
// To open a file    
 public void openFile()
    {
        try
        {
            output=new Formatter("clients.txt");
        }
        catch(Exception e)
        {
            System.out.println("You do not have write access to this file");
            System.exit(1);
            
        }
    }
    
// To add records to the file   
 public void addRecords()
    {
        AccountRecord record=new AccountRecord();
        
        Scanner input=new Scanner(System.in);
        System.out.println("To terminate input, type  then press ");
        
        System.out.println("Enter Account Number, First Name, Last Name and Balance");
        
        while(input.hasNext())
        {
            try
            {
                record.setAccount(input.nextInt());
                record.setFirstname(input.next());
                record.setLastname(input.next());
                record.setBalance(input.nextDouble());
                
                if(record.getAccount() > 0)
                {
                    output.format("%d %s %s %.2f", record.getAccount(),record.getFirstname(),record.getLastname(),record.getBalance());
                }
                else
                {
                    System.out.println("Account Number must greater than 0");
                }
            }
            catch(Exception e)
            {
                System.out.println("Error writing to File");
            }
        }
        
        
        
    }
    
// To close File    
public void closeFile()
        {
            if(output !=null)
            {
                output.close();
            }
            
        }
}
Now take a Main class and create an object for CreateTextFile and execute the program.
//Execution of the application
package seqfiles;

/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        CreateTextFile application=new CreateTextFile();
        
        application.openFile();
        application.addRecords();
        application.closeFile();
    }

}
Now you can see a text file will be created in your source code directory and which contains the Information of AccountRecord class. Reading Data from a Sequential-Access Text File For this we need to write another program which implements Scanner class of java.util package. Let us see how it works.
//This program reads a text file and display each record
package seqfiles;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author Administrator
 */
public class ReadTextFile {
    
    private Scanner input;
    
   // To open a file
    public void openFile()
    {
        try
        {
            input=new Scanner(new File("clients.txt"));
        }
        catch(Exception e)
        {
            System.out.println("Error opening File");
                        
        }
    }
    
    // To read Record from the file
    
    public void readRecord()
    {
        AccountRecord record=new AccountRecord();
        
        System.out.printf("%s %s %s %s\n", "Account","First Name","Last Name","Balance");
        
        try
        {
            while(input.hasNext())
            {
                record.setAccount(input.nextInt());
                record.setFirstname(input.next());
                record.setLastname(input.next());
                record.setBalance(input.nextDouble());
                
                System.out.printf("%d %s %s %.2f", record.getAccount(),record.getFirstname(),record.getLastname(),record.getBalance());
            }
        }
        catch(Exception e)
        {
            input.close();
        }
    }
    
    // To close File
    public void closeFile()
    {
        if(input !=null)
        {
            input.close();
        }
    }

}
In order to implement this, we need to create an object for the above class then the output will contains the record of the file clients.txt.
//Execution of the application
package seqfiles;

/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
                
        ReadTextFile application=new ReadTextFile();
        application.openFile();
        application.readRecord();
        application.closeFile();
    }

}

20.Files and Streams

Monday, April 12, 2010 Posted by Sudarsan 1 comments
Files and Streams

In some cases, data inputs are stored in files. Moreover, there are also instances when we want to store the output of a certain program to a file. In a computerized enrollment system, the student data that may be used as an input to the system is most probably stored in a particular file.

Then, one possible output of the system is the information about the subjects enrolled in by the students. Again, the output in this case may preferably be stored in a file. As seen in this application, there is a need for reading from a file and writing to a file. You will learn about file input and output in this sect ion.

Input and output

The Java library classes for IO are divided by input and output, as you can see by looking at the online Java class hierarchy with your Web browser. By inheritance, all classes derived from InputStream have basic methods called read( ) for reading a single byte or array of bytes. Likewise, all classes derived from OutputStream have basic methods called write( ) for writing a single byte or array of bytes.

However, you won’t generally use these methods; they exist so more sophisticated classes can use them as they provide a more useful interface. Thus, you’ll rarely create your stream object by using a single class, but instead will layer multiple objects together to provide your desired functionality. The fact that you create more than one object to create a single resulting stream is the primary reason that Java’s stream library is confusing.

It’s helpful to categorize the classes by their functionality. The library designers started by deciding that all classes that had anything to do with input would be inherited from InputStream and all classes that were associated with output would be inherited from OutputStream..

Types of InputStream

InputStream’s job is to represent classes that produce input from different sources. These sources can be (and each has an associated subclass of InputStream):

1. An array of bytes

2. A String object

3. A file

4. A “pipe,” which works like a physical pipe: you put things in one end and they come out the other

5. A sequence of other streams, so you can collect them together into a single stream

6. Other sources, such as an Internet connection.

In addition, the FilterInputStream is also a type of InputStream, to provide a base class for "decorator" classes that attach attributes or useful interfaces to input streams.


The File class

The File class has a deceiving name – you might think it refers to a file, but it doesn’t. It can represent either the name of a particular file or the names of a set of files in a directory. If it’s a set of files, you can ask for the set with the list( ) method, and this returns an array of String.

It makes sense to return an array rather than one of the flexible collection classes because the number of elements is fixed, and if you want a different directory listing you just create a different File object. In fact, “FilePath” would have been a better name. This section shows a complete example of the use of this class.

Creating File Objects

File objects are frequently used with objects of other java.io classes to specify files or directories to manipulate.

Class File provides four constructors. The constructor specifies the name of a file or directory to associate with the File object. The name contain path information as well as a file or directory.

public File(String name)

The constructor uses argument pathToName to locate the file or directory specified by name.

public File(String pathToName, String name)

The constructor uses an existing File object directory to locate the file or directory specified by name.

public File(File directory, String name)

The constructor uses the URI object to locate the file, which is used to locate web sites. For example, http://www.javacircuit.blogspot.com is the URL of javacircuit website.

public File(URI uri)


Now let’s move on to one example which demonstrates File class methods.


//File class and its Methods

package files;
// Inorder to use Streams we need to import the fallowing package
import java.io.*;


/**
 *
 * @author Administrator
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        File f=new File("D:\\BSNL.txt");
        
        getFile("File Name : "+f.getName());
        getFile("Path : "+f.getPath());
        getFile("Absolute Path: "+f.getAbsolutePath());
        getFile("Parent : "+f.getParent());
        getFile(f.exists() ? "File Exists" : "Does not exists");
        getFile(f.canWrite() ? "is Writable" : "Not Writable");
        getFile(f.canRead() ? "is readable" : "Not readable");
        getFile("is "+ (f.isDirectory() ? " " : "not" + "a directory"));
        getFile(f.isFile() ? "is normal File" :"Not a normal File");
        getFile("File Last Modified on" +f.lastModified() );
        getFile("File Size : "+f.length()+"bytes");
        
    }

    static void getFile(String s)
    {
        System.out.println(s);
    }
}

When we compile this program we can get the fallowing output

File Name : BSNL.txt
Path : D:\BSNL.txt
Absolute Path: D:\BSNL.txt
Parent : D:\
File Exists
is Writable
is readable
is nota directory
is normal File
File Last Modified on1243060523708
File Size : 192bytes


In order to use more methods of File class just go to java.io package in Java API.

In the next post we will discuss more about Files, that's all Folks !!!