File Operations In Java

15 April 2007

Through file handling, we can read data from and write data to files besides doing all sorts of other operations. Java provides a number of methods for file handling through different classes which are a part of the “java.io” package.

The question can arise in the mind of a new programmer as to why file-handling is required. The answer of this question would be in two parts, why do we need to read data from the files and why do we need to save it (write it) to a file.

To answer the first part, Let us suppose that we have a very large amount of data which needs to be input into a program, Something like a 1000 records, If we start inputting the data manually and while we are in half-way through the process, there is a power-failure, then once power is restored, the entire data has to be input again. This would mean a lot of extra work, an easier approach would be to write all the records in a file and save the file after writing 10 or so records, in this case even if there is a power-failure, only some records would be lost and once power is restored, there would be only a few records that would need to be input again. Once all the records are saved in that file, the file-name can be passed to the program, which can then read all the records from the file.
For the second part, consider a system which needs to record the time and name of any error that occurs in the system, this can be achieved through saving the data into a file and the administrator can view the file any time he/she wishes to view it.

If you use a “/” in a path definition in Java in Windows, the path would still resolve correctly and if you use the Windows conventional “\”, then you have to place two forward slashes “\\” as a single “\” would be taken as an escape-suquence.

The “File” class in Java defines many useful methods, here is a program which demonstrates some of these methods.

 
import java.io.*;
 
public class streams
{
	public static void main(String []args)
	{
		File f1=new File("Folder/FILE");
		File f2=new File("Folder/FILE1");
 
		String s;
 
		if(f1.exists())
		{
			if(f1.isFile())
			{
				System.out.println("File Name is "+f1.getName());
				s=f1.getParent();
 
				File f3=new File(s);
 
				f1.renameTo(new File("Folder/abc"));
 
				f2.delete();
 
				if (f3.isDirectory())
				{
					System.out.println(f2.getPath());
				}
			}
			else
			{
				System.out.println("Not a File");
			}
		}
	}
}
The output of the program is:
 
File Name is FILE
Folder

If successfully run , the ” FILE ” file inside the folder ” Folder ” will be renamed to ” abc ” and the ” FILE1 ” file will be deleted.

Here is an example of a program that reads its own first six bytes, we have:

 
//0123
 
import java.io.*;
 
public class read
{
	public static void main(String []args)
	{
		int s=6;
		int b[]=new int[6];
		char c[]=new char[6];
		try
		{
			FileInputStream f = new FileInputStream("read.java");
 
			for (int i=0; i<6; i++)
			{
				b[i] = f.read();
				c[i] = (char) b[i];
			}
 
			System.out.println("First 6 bytes of the file are :");
			for (int i=0;i<6;i++)
				System.out.print(b[i]+" ");
 
			System.out.println("nnFirst 6 Bytes as characters  :");
			for (int i=0;i<6;i++)
				System.out.print(c[i]);
		}
		catch (Exception e)
		{
			System.out.println("Error");
		}
	}
}
 
This program produces the following output:
 
First 6 bytes of the file are :
47 47 48 49 50 51
 
First 6 Bytes as characters are :
 
//0123

Notice that the FileInputStream object is created inside a try-catch block since if the specified-file does not exist, an exception is raised.

In the same way to write data to a file byte-by-byte, we have:

 
import java.io.*;
 
public class witer
{
	public static void main(String []args) throws IOException
	{
		String s="Hello";
 
		byte b[]=s.getBytes();
 
		FileOutputStream f=new FileOutputStream("file.txt");
 
		int i=0;
		while(i
		{
			f.write(b[i]);
			i++;
		}
	}
}

If the file called file.txt does not exist, it is automatically created.

If we place a true in the constructor for the FileOutputStream, then the file would be opened in append mode.
Note: All file paths used here are relative paths , Use absolute path or add the relative path to the classpath, Copy the folders to the bin folder

del.icio.us:File Operations In Java  digg:File Operations In Java  spurl:File Operations In Java  wists:File Operations In Java  simpy:File Operations In Java  newsvine:File Operations In Java  blinklist:File Operations In Java  furl:File Operations In Java  reddit:File Operations In Java  fark:File Operations In Java  blogmarks:File Operations In Java  Y!:File Operations In Java  smarking:File Operations In Java  magnolia:File Operations In Java  segnalo:File Operations In Java  gifttagging:File Operations In Java

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: File Operations In Java

3 Responses to “File Operations In Java”

  1. kanchana Says:

    could u please put how to handle token by token in files..
    for example if a file contains name and id, i want to retrive id only for comparsion ..how can i perform it..

  2. nda Says:

    thanks …. this tuts very good!!!! two thumbs up!!!!

  3. Sheetal Malhotra Says:

    Hii everybody…can anyone please tell me how to read floating point values line by line from a file and write them into another file…waiting for ur replies…thanks and regards.

Leave a Reply