by Dinesh Thakur

Java makes available a set of classes and methods that allows you to read from and write to files. Java supports both streams and methods to read from and write to file respectively.

 

Example: Read file using FilelnputStream

 

import java.io.*;

class ShowFile

{

public static void main(String ar[]) throws IOException

{

int ch;

FileInputStream finObj;

try

{

finObj = new FileInputStream("ShowFile.java");

}

catch(FileNotFoundException e)

{

System.out.println("File Not Found");

return;

}

do

{

ch = finObj.read();

if(ch != -1)

System.out.print((char) ch);

} while(ch != -1);

finObj.close();

}

}

 

Output

 

 Reading and Writing on Files

Print contents of own source file, read character by character and write character by character.

 

Example: Read file using FileReader

 

import java.io.*;

class FileRead

{

public static void main(String arg[]) throws IOException

{

FileReader frObj = new FileReader("FileRead.java");

BufferedReader brObj = new BufferedReader(frObj);

String str;

while ((str = brObj.readLine ())!=null)

System.out.println(str);

frObj.close();

}

}

 

Output

 File Read

Read the file content line by line, and print in the same manner.

 

Example: Writing data using FileOutputStream

 

import java.io.*;

class CopyFile

{

public static void main(String arg[]) throws IOException

{

int i;

FileInputStream finObj;

FileOutputStream foutObj;

try

{

try

{

finObj = new FileInputStream(arg[0]);

}

catch(FileNotFoundException e)

{

System.out.println("File " + arg[0] + " not Found");

return;

}

 

try

{

foutObj = new FileOutputStream(arg[1]);

}

catch(FileNotFoundException e)

{

System.out.println("File" +arg[1]+" not found");

return;

}

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Argument missing");

return;

}

 

try

{

do

{

i = finObj.read();

if(i != -1)

foutObj.write(i);

}while(i != -1);

}

catch(IOException e)

{

System.out.println("Some file error occurd");

}

finObj.close();

foutObj.close();

}

}

 

Output:

 

 CopyFile

Copy content of a.txt to b.txt

 

It is clear form the output window given above that content of a.txt has been copied to b.txt.

 

Example: Writing data using FileWriter

 

import java.io.*;

public class WriteFile

{

public static void main(String[] args) throws IOException

{

File inputFileObj = new File("a.txt");

File outputFileObj = new File("b.txt");

FileReader finObj = new FileReader(inputFileObj);

FileWriter foutObj = new FileWriter(outputFileObj);

int c;

while ((c = finObj.read()) != -1)

foutObj.write(c);

finObj.close();

foutObj.close();

}

}

 

Output:

 

 Write File

Copy content of a.txt to b.txt