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);
}
}
}

3 comments:

Anonymous said...

While this will copy a file, it's probably not the most performant to do it one byte at a time. There are other methods that you can use to read/write multiple bytes at a time.

Rakesh Nerella said...

Even I feel, the above code might not give the best performance. Have a look at the code in this link :
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.

Unknown said...

Well that's true.. but sometimes you knw the file is very small and just need some way to do read write. So, when the file size is pretty small you really dont need to worry about performance...