请问如何拷贝一个文件:?

xmayxmei 2006-03-07 02:45:17
如给出:“E:/eclipse3.02/2024/200386-4917.jpg”
怎样将该文件拷贝到另外一个目录?
若子目录不存在自动创建。“F:/MYFILES/2024/200386-4917.jpg”
...全文
104 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
wfhlxl 2006-03-07
  • 打赏
  • 举报
回复
public void CopyFile(String in , String out) throws Exception {
File inf = new File(in);

if(!inf.exists())
return;
File outf = new File(out);

String outPath[] = out.split("/");
String tmp =outPath[0];
for(int i =1; i< outPath.length -1;i++)
{ tmp = tmp +"/" + outPath[i];
outf =new File(tmp +"/");
if(!outf.exists())
{
outf.mkdir();

}

}
outf =new File(out);
FileInputStream fis = null;
try {
fis = new FileInputStream(inf);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream fos = null;

try {
fos = new FileOutputStream(outf);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

byte[] buf = new byte[1024];
int i = 0;
while((i=fis.read(buf))!=-1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
//call :
try {
a.CopyFile("d:/aa/aa.bmp","d:/aa/bb/aa.bmp");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xmayxmei 2006-03-07
  • 打赏
  • 举报
回复
楼上,我没有这个目录\\2024\\要怎么搞?
因为是动态的。所以所有的目录要动态创建。
interpb 2006-03-07
  • 打赏
  • 举报
回复
E:\\\ 改为E:\\ 不好意思自己还写错 还让你注意!
interpb 2006-03-07
  • 打赏
  • 举报
回复
FileInputStream fin = new FileInputStream(“E:\\\eclipse3.02\\2024\\200386-4917.jpg”
");
File fcopy = new File("F:\\\MYFILES\\2024\\200386-4917.jpg");
fcopy.createNewFile() ;

FileOutputStream fout = new FileOutputStream(fcopy);

int b;
while((b=fin.read())!=-1){
fout.write(b);

注意文件分隔符

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧