JAVA中怎样利用递归算法删除或复制目录?
接触JAVA不久,碰到此问题的思路还是有些模糊,怎样能让File的一个实例对象好像只能指向一个文件,怎样才能指向多个文件,望高手能赐教!~
------解决方案--------------------很久之前写的,可以参考一下。
----------------------
private void moveFiles(String source, String target, boolean delete) throws
IOException {
File sourceFile = new File(source);
if (sourceFile.exists())
{
if (sourceFile.isFile())
{
moveFile(source, target, delete);
}
else if (sourceFile.isDirectory())
{
File targetFile = new File(target);
if (!targetFile.exists())
{
targetFile.mkdir();
}
String [] files = sourceFile.list();
for (int i=0; i <files.length; i++)
{
moveFiles(source + File.separator + files[i], target + File.separator + files[i], delete);
}
if (delete)
{
sourceFile.delete();
}
}
else {}
}
}
private void moveFile(String in, String out, boolean delete) throws IOException
{
File inFile = new File(in);
if(inFile.exists())
{
FileInputStream fin = new FileInputStream(in);
FileOutputStream fout = new FileOutputStream(out);
int i = 0;
while((i = fin.read(dataBuffer)) != -1) {
fout.write(dataBuffer, 0, i);
}
fin.close();
fout.close();
if (delete)
{
inFile.delete();
}
}
}
----------------------