public class CopyFile
{
public static void main(String[] args) throws Exception
{
String source = "c:\\test";
String dest = "d:\\trytest";
write2Dir(source,dest);
}
public static void write2file(File SourceFile,File DestFile)
{
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try
{
inputStream = new BufferedInputStream(new FileInputStream(SourceFile));
outputStream = new BufferedOutputStream(new FileOutputStream(DestFile));
byte[] buf = new byte[1024];
int len = 0;
while((len = inputStream.read(buf)) != -1)
{
outputStream.write(buf,0,len);
}
outputStream.flush();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(inputStream != null)
inputStream.close();
if(outputStream!=null)
outputStream.close();
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
}
public static void write2Dir(String sourceDir,String desDir) throws IOException
{
(new File(desDir)).mkdirs();
File[] files = (new File(sourceDir)).listFiles();
for(int i=0; i<files.length; i++)
{
if(files.isFile())
{
File SourceFile = files;
File DestFile = new File(new File(desDir).getCanonicalPath()+(String)File.separator+files.getName());
write2file(SourceFile,DestFile);
}
if(files.isDirectory())
{
String source = sourceDir + File.separator + files.getName();
String dest = desDir + File.separator + files.getName();
write2Dir(source, dest);
}
}
}
}
|
|