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 = in.read(buf)) >= 0) { out.write(buf, 0, len); } // close both streams in.close(); out.close(); }
One Ping to “How do I copy a file using Java?”
Array ( [0] => WP_Comment Object ( [comment_ID] => 54 [comment_post_ID] => 162 [comment_author] => How can I return an image using a servlet? | web development helpdesk [comment_author_email] => [comment_author_url] => http://helpdesk.objects.com.au/java/how-can-i-return-an-image-using-a-servlet [comment_author_IP] => 125.214.65.236 [comment_date] => 2009-04-22 02:40:27 [comment_date_gmt] => 2009-04-22 02:40:27 [comment_content] => [...] How-do-i-copy-a-file-using-java [...] [comment_karma] => 0 [comment_approved] => 1 [comment_agent] => Incutio XML-RPC -- WordPress/2.6.5 [comment_type] => pingback [comment_parent] => 0 [user_id] => 0 [children:protected] => Array ( ) [populated_children:protected] => 1 [post_fields:protected] => Array ( [0] => post_author [1] => post_date [2] => post_date_gmt [3] => post_content [4] => post_title [5] => post_excerpt [6] => post_status [7] => comment_status [8] => ping_status [9] => post_name [10] => to_ping [11] => pinged [12] => post_modified [13] => post_modified_gmt [14] => post_content_filtered [15] => post_parent [16] => guid [17] => menu_order [18] => post_type [19] => post_mime_type [20] => comment_count ) ) ) 2 Responses to “How do I copy a file using Java?”
-
latif Says:
September 27th, 2012 at 2:22 pmthank you
Leave a Reply
You must be logged in to post a comment.
April 22nd, 2009 at 2:40 am
[…] How-do-i-copy-a-file-using-java […]