File copy

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.*;

publicclass CopyFile

{

// Copies all files under srcDir to dstDir.

// If dstDir does not exist, it will be created.

publicvoid 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[i]),

new File(dstDir, children[i]));

}

}else{

copyFile(srcDir, dstDir);

}

}

publicstaticvoid 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");

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

}

}

privatevoid 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 =newbyte[1024];

int len;

while ((len = in.read(buf)) > 0)

{

out.write(buf, 0, len);

}

in.close();

out.close();

}

}

[4446 byte] By [thanua] at [2007-11-27 8:59:55]
# 1
any idea?
thanua at 2007-7-12 21:28:01 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
hi Thanuja,change this lineFile dstDir=new File("../../test");instead of File dstDir=new File("D:/Thanuja/test");bala
art84a at 2007-7-12 21:28:01 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3
thanks. will chk it out. but why to change like this?File dstDir=new File("../../test");Thanks,Thanuja.
thanua at 2007-7-12 21:28:01 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4
Iam stuck with this. why is it iam getting this error while copying a file but not directory.ThanksThanuja.
thanua at 2007-7-12 21:28:01 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...