Hi,
I am trying to copy a file in java but not understanding what i am missing?
Can anyone help me with this?
Hi,
I am trying to copy a file in java but not understanding what i am missing?
Can anyone help me with this?
Try this code!
Code:import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } }
Copy a File
Code:import java.io.*; public class jCOPY { public static void main(String args[]){ try { jCOPY j = new jCOPY(); j.CopyFile(new File(args[0]),new File(args[1])); } catch (Exception e) { e.printStackTrace(); } } public void CopyFile(File in, File out) throws Exception { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); byte[] buf = new byte[1024]; int i = 0; while((i=fis.read(buf))!=-1) { fos.write(buf, 0, i); } fis.close(); fos.close(); } }
Java does not provide a standard method to copy a file. To implement copying you need to read all bytes from source file and write to destination. The read() method will return -1 when of is reached, otherwise it returns the number of bytes read.
Code:1. public static void copy(File source, File destination) 2. throws IOException 3. { 4. // Open file to be copied 5. InputStream in = new FileInputStream(source); 6. 7. // And where to copy it to 8. OutputStream out = new FileOutputStream(destination); 9. 10. // Read bytes and write to destination until eof 11. 12. byte[] buf = new byte[1024]; 13. int len = 0; 14. while ((len = in.read(buf)) > 0) 15. { 16. out.write(buf, 0, len); 17. } 18. 19. // close both streams 20. 21. in.close(); 22. out.close(); 23. }
Bookmarks