Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.

Tuesday, January 8, 2008

Files reading and writing in Java

Lot of times we need to read or write files using java code.

Here is an useful example:
import java.io.*;

class FileCopyUtility
{
public static void main(String[] args)
{
try
{
//create the file objects from the source and target file names
File fileToRead = new File("source.txt");
File fileToWrite = new File("target.txt");

//create File Input stream reader and writer
FileInputStream streamIn = new FileInputStream(fileToRead);
FileOutputStream streamOut = new FileOutputStream(fileToWrite);

int c;
//this loop will run till there is something to read in the input stream
while ((c = streamIn.read()) != -1)
{
//read stream will be written to the output stream
streamOut.write(c);
}

//close the file input and output streams once the copy operation is done.
streamIn.close();
streamOut.close();
}
catch (FileNotFoundException e)
{
System.err.println("FileCopy: " + e);
}
catch (IOException e)
{
System.err.println("FileCopy: " + e);
}
}
}
Post a Comment