sri
Moderator

Joined: 28 Jan 2006
Posts: 379
Location: Hyderabad , India

|
File-handling under Java
One of the first things a programmer learns with a new language is how to read and write to files, since the saving and loading of data will be an important feature of most software he or she will eventually develop using that language.
Java offers extensive - yet easy to use - file handling classes that make it a breeze to read and write files. In this tutorial, we'll start by covering the basics of file input and output, as well as covering some associated topics, such as trapping exceptions and I/O errors. I'll present two Java examples - one covering file output, and one covering file input
> FileOutputDemo.java
> FileInputDemo.java
File output
Our first example will be a program that writes a string to a file. In order to use the Java file classes, we must import the Java input/output package (java.io) in the following manner
import java.io.*;
Inside the main method of our program, we must declare a FileOutputStream object. For those familiar with C, a FileOutputStream is analogous to a file handle. When we send a stream (or sequence) of data to the FileOutputStream handle, data will be written to disk.In Java, there exists a large number of extensions to the standard input and output stream classes. This is handy, as the basic input and output streams deal only with the transfer of bytes - not the easiest way for us to write out data. There's a wide variety of streams to choose from : if we were writing data such as bytes, integers, floats, or other "data" orientated types, we might choose the DataOutputStream, whereas for text we'd use the PrintStream class.
In this case, we wish to write a string to the file, and so we create a new PrintStream object that takes as its constructor the existing FileOutputStream. Any data we send from PrintStream will now be passed to the FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it a string, and then close the connection.
/*
*
* FileOutputDemo
*
* Demonstration of FileOutputStream and
* PrintStream classes
*
*/
import java.io.*;
class FileOutputDemo
{
public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
p = new PrintStream( out );
p.println ("This is written to a file");
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
After executing the program, and providing a valid filename, you'll see how easy it is to read and process files. There are a wide variety of methods supported by the DataInputStream class, which make it easy to read in almost any data type. For further information, consult your Java API.
- srikanth dhanwada
|