Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

File copy

843838Jun 27 2007 — edited Jun 28 2007
Hi,

Following is a program to copy directory and files. Program works fine if i copy the directory (subdirectories and files inside are also copied). But if the source is a file instead of directory i get the following error:

java.io.FileNotFoundException: D:\Thanuja\test (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at CopyFile.copyFile(CopyFile.java:55)
at CopyFile.copyDirectory(CopyFile.java:27)
at CopyFile.main(CopyFile.java:44)

import java.nio.*;
import java.nio.channels.*;
import java.io.*;
    
    public class CopyFile 
    {
     
     // Copies all files under srcDir to dstDir.
    // If dstDir does not exist, it will be created.
       
       public void copyDirectory(File srcDir, File dstDir) throws IOException 
       {
           //System.out.println("Inside");
        if (srcDir.isDirectory())
        {
            if (!dstDir.exists()) {
                dstDir.mkdir();
            }
    
            String[] children = srcDir.list();
            for (int i=0; i<children.length; i++) {
                copyDirectory(new File(srcDir, children),
new File(dstDir, children[i]));
}
} else {

copyFile(srcDir, dstDir);
}
}


public static void main(String args[])
{
// File srcDir=new File("D:/Thanuja/Samples/"); //To copy directory -- this works well
File srcDir=new File("D:/Thanuja/ToolTip.jsp"); //To copy file
if(srcDir.isDirectory())
System.out.println("Dirchk");
else if(srcDir.isFile())
System.out.println("Filechk");

File dstDir=new File("D:/Thanuja/test/");

CopyFile cp=new CopyFile();
try {
cp.copyDirectory(srcDir,dstDir);
} catch (IOException ex) {
ex.printStackTrace();
}
}

private void copyFile(File srcDir, File dstDir) throws FileNotFoundException, IOException {

//System.out.println("dstDir:"+dstDir);

InputStream in = new FileInputStream(srcDir);
OutputStream out = new FileOutputStream(dstDir);

// 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();


}



}


Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 26 2007
Added on Jun 27 2007
4 comments
109 views