Write a program to copy a file a.txt to another file b.txt
If you need to read characters, you should use a character stream. A buffered stream reads multiple lines at a time and hence is more efficient.
In this example we are using a FileInputStream for reading the file and FileOutputStream for writing to a file. We read one byte at a time and write it back to the output file.
Note the use of finally which ensures that we safely close both streams.
File operations throw IOException if there is an error in opening/reading/writing. Instead of handling the exception, we are just throwing it.
End of file :
When we reach the end of file, read() method returns a -1. -1 is the end of file character. So we continue reading the bytes until a -1 is read.import java.io.*; public class filecopy { public static void main(String args[]) throws IOException { String filename1 = "a.txt"; String filename2 = "b.txt"; FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(filename1); out = new FileOutputStream(filename2); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
Comments
Post a Comment