Difference between revisions of "Copy a file"

From CodeCodex

m (+highlightsyntax)
Line 1: Line 1:
 
==Implementations==
 
==Implementations==
 
===Java===
 
===Java===
<pre>
+
<HIGHLIGHTSYNTAX language="java122">
 
     // Copies src file to dst file.
 
     // Copies src file to dst file.
 
     // If the dst file does not exist, it is created
 
     // If the dst file does not exist, it is created
Line 17: Line 17:
 
         out.close();
 
         out.close();
 
     }
 
     }
</pre>
+
</HIGHLIGHTSYNTAX>
 
* Original Source: [http://javaalmanac.com/egs/java.io/pkg.html?l=rel#Files The Java Developers Almanac 1.4]
 
* Original Source: [http://javaalmanac.com/egs/java.io/pkg.html?l=rel#Files The Java Developers Almanac 1.4]
  
 
Copies or moves a file without a loop.  Although I'm not sure, I believe using a FileChannel allows the OS to short-circuit the operation (without actually transferring the data through Java code).
 
Copies or moves a file without a loop.  Although I'm not sure, I believe using a FileChannel allows the OS to short-circuit the operation (without actually transferring the data through Java code).
  
<HIGHLIGHTSYNTAX>
+
<HIGHLIGHTSYNTAX language="java122">
 
     public void copy(File src, File dest, boolean move) throws Exception {
 
     public void copy(File src, File dest, boolean move) throws Exception {
 
// Create channel on the source
 
// Create channel on the source

Revision as of 18:15, 24 February 2007

Implementations

Java

<HIGHLIGHTSYNTAX language="java122">

   // Copies src file to dst file.
   // If the dst file does not exist, it is created
   void copy(File src, File dst) throws IOException {
       InputStream in = new FileInputStream(src);
       OutputStream out = new FileOutputStream(dst);
   
       // Transfer bytes from in to out
       byte[] buf = new byte[1024];
       int len;
       while ((len = in.read(buf)) > 0) {
           out.write(buf, 0, len);
       }
       in.close();
       out.close();
   }

</HIGHLIGHTSYNTAX>

Copies or moves a file without a loop. Although I'm not sure, I believe using a FileChannel allows the OS to short-circuit the operation (without actually transferring the data through Java code).

<HIGHLIGHTSYNTAX language="java122">

   public void copy(File src, File dest, boolean move) throws Exception {

// Create channel on the source

       FileChannel srcChannel = new FileInputStream(src).getChannel();
   	// Create channel on the destination
   	FileChannel dstChannel = new FileOutputStream(dest).getChannel();
   
   	// Copy file contents from source to destination

dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

   	// Close the channels

srcChannel.close();

       dstChannel.close();
       if(move) src.delete();	
   }

</HIGHLIGHTSYNTAX>