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