Monday, 27 January 2014

Reading and Writing Files in java

how to use reading and  writing file :fileInputStream:FileOutputStream.....


Reading and Writing Files



Java provides a number of classes and methods that allow you to read and write files. In Java, all files are byte-oriented, and Java provides methods to read and write bytes from and to a file Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files.

Syntax :


Syntax of FileInputStream And FileOutputStream

FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException


Here, fileName specifies the name of the file that you want to open. When you create an input stream, if the file does not exist, then FileNotFoundException is thrown. For output streams, if the file cannot be created, then FileNotFoundException is thrown.

 void close( ) throws IOException


When you are done with a file, you should close it by calling close( ). It is defined by both FileInputStream and FileOutputStream.

int read( ) throws IOException

To read from a file, you can use a version of read( ) that is defined withinFileInputStream.


void write(int byteval) throws IOException

To write to a file, you can use the write( ) method defined by FileOutputStream.


Example


/* Display a text file.To use this program, specify the name of the file that you want to see. For example, to see a file called TEST.TXT, use the following command line. java ShowFile TEST.TXT */

import java.io.*;
class ShowFile 
{
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try
 {
fin = new FileInputStream(args[0]);

catch(FileNotFoundException e)
 {
System.out.println("File Not Found");
return;

catch(ArrayIndexOutOfBoundsException e)
 {
System.out.println("Usage: ShowFile File");
return;
}
Chapter 13: I/O, Applets, and Other Topics 295
// read characters until EOF is encountered
do 
{
i = fin.read();
if(i != -1) System.out.print((char) i);

while(i != -1);
fin.close();
}
}




















































































No comments :

Post a Comment