File Copy Tutorial Java
Using finally block to close streams
For real time programming, the above program is modified where file handles are closed in finally block. finally block statements are guaranteed of execution even if the exceptions thrown by different constructors and methods are not handled successfully. It is the best practice.
import java.io.*;
public class FileToFile1
{
public static void main(String args[])
{
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
fis = new FileInputStream("pqr.txt");
fos = new FileOutputStream("xyz.txt");
int k;
while( ( k = fis.read() ) != -1 )
{
fos.write(k);
System.out.print((char) k);
}
}
catch(FileNotFoundException e)
{
System.out.println("File does not exist. " + e);
}
catch(IOException e)
{
System.out.println("Some I/O problem. " + e);
}
finally
{
try
{
if(fos != null)
fos.close();
if(fis != null)
fis.close();
}
catch(IOException e)
{
System.out.println("File is not closed properly. " + e);
}
}
}
}
if(fos != null)
fos.close();
The above statement is another good programming practice, to check whether FileOutputStream object is created or not (closing when not created raises exception). It is done by comparing fos with null.
Learn performance tips in file copying
Pages: 1 2
Sir i just did the above program the output is “File does not Exist” even though i created two text files in my folder what is this exception where to create the txt files??
The general mistake the learners does is this only. Check the extension to the files; they will be definitely of the form abc.txt.txt (give dir command) or you must have saved the files in a different folder.