Files reading and writing in Java
Lot of times we need to read or write files using java code.
Here is an useful example:
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);
}
}
}

Comments
http://forum.java.sun.com/thread.jspa?threadID=484871&messageID=2267156
It reads file contents to a String. We can extend that code to write those contents to a different file.