Sep 23

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 retuirn -1 when eof is reached, otherwise it returns the number of bytes read.

public static void copy(File source, File destination)
   throws IOException
   // Open file to be copied
   InputStream in = new FileInputStream(source);

   // And where to copy it to
   OutputStream out = new FileOutputStream(destination);

   // Read bytes and write to destination until eof

   byte[] buf = new byte[1024];
   int len = 0;
   while ((len = >= 0)
      out.write(buf, 0, len);

   // close both streams


written by objects \\ tags: ,

One Ping to “How do I copy a file using Java?”

  1. How can I return an image using a servlet? | web development helpdesk Says:

    […] How-do-i-copy-a-file-using-java […]

One Response to “How do I copy a file using Java?”

  1. latif Says:

    thank you

Leave a Reply

You must be logged in to post a comment.