黑马程序员技术交流社区
标题:
将盘符下的所以文件复制到另外的盘符下。
[打印本页]
作者:
黄晓鑫
时间:
2014-3-29 21:14
标题:
将盘符下的所以文件复制到另外的盘符下。
求代码啊!
作者:
itpower
时间:
2014-3-29 21:28
class CopyFilesDemo2
{
public static void main(String[] args)
{
File sour = new File("e:\\Open_Sourse");
File targ = new File("e:\\copy");
targ.mkdir();
findFile(sour,targ);
}
public static void findFile(File sour,File targ)
{
File[] files = sour.listFiles();
for(File file:files)
{
if(file.isDirectory())
{
String dir = file.getName();
File newFile = new File(targ+"\\"+dir);
newFile.mkdirs();
findFile(file,newFile);
}
else
{
try
{
if(file.getName().endsWith("java"))
{
String fileName = file.getName();
String[] newFileName = fileName.split("\\.");
File new2File = new File(targ+"\\"+newFileName[0]+".txt");
new2File.createNewFile();
copyFile(file,new2File);
}
}
catch (IOException e1)
{
e1.printStackTrace();
throw new RuntimeException("文件复制失败!");
}
}
}
}
public static void copyFile(File sour,File targ)
{
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
if(!sour.isFile())
throw new RuntimeException("sour不是一个文件");
fis = new FileInputStream(sour);
fos = new FileOutputStream(targ);
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf))!=-1)
{
fos.write(buf,0,len);
}
}
catch (IOException e)
{
e.printStackTrace();
throw new RuntimeException("文件复制失败!");
}finally
{
try
{
if(fis != null)
fis.close();
}
catch (IOException efr)
{
efr.printStackTrace();
}
try
{
if(fos != null)
fos.close();
}
catch (IOException efw)
{
efw.printStackTrace();
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2