导航:首页 > 编程语言 > filecopyjava

filecopyjava

发布时间:2025-05-09 21:43:56

㈠ 在java中,怎样将图片从一个地方复制到另一个地方(最好有代码


JDK宝典里有这样的一段代码,你调用File方法就可以了:

/**
* 复制单个文件, 如果目标文件存在,则不覆盖。
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean File(String srcFileName, String destFileName){
return CopyFileUtil.File(srcFileName, destFileName, false);
}

/**
* 复制单个文件
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean File(String srcFileName,
String destFileName, boolean overlay) {
//判断原文件是否存在
File srcFile = new File(srcFileName);
if (!srcFile.exists()){
System.out.println("复制文件失败:原文件" + srcFileName + "不存在!");
return false;
} else if (!srcFile.isFile()){
System.out.println("复制文件失败:" + srcFileName + "不是一个文件!");
return false;
}
//判断目标文件是否存在
File destFile = new File(destFileName);
if (destFile.exists()){
//如果目标文件存在,而且复制时允许覆盖。
if (overlay){
//删除已存在的目标文件,无论目标文件是目录还是单个文件
System.out.println("目标文件已存在,准备删除它!");
if(!DeleteFileUtil.delete(destFileName)){
System.out.println("复制文件失败:删除目标文件" + destFileName + "失败!");
return false;
}
} else {
System.out.println("复制文件失败:目标文件" + destFileName + "已存在!");
return false;
}
} else {
if (!destFile.getParentFile().exists()){
//如果目标文件所在的目录不存在,则创建目录
System.out.println("目标文件所在的目录不存在,准备创建它!");
if(!destFile.getParentFile().mkdirs()){
System.out.println("复制文件失败:创建目标文件所在的目录失败!" );
return false;
}
}
}
//准备复制文件
int byteread = 0;//读取的位数
InputStream in = null;
OutputStream out = null;
try {
//打开原文件
in = new FileInputStream(srcFile);
//打开连接到目标文件的输出流
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
//一次读取1024个字节,当byteread为-1时表示文件已经读完
while ((byteread = in.read(buffer)) != -1) {
//将读取的字节写入输出流
out.write(buffer, 0, byteread);
}
System.out.println("复制单个文件" + srcFileName + "至" + destFileName + "成功!");
return true;
} catch (Exception e) {
System.out.println("复制文件失败:" + e.getMessage());
return false;
} finally {
//关闭输入输出流,注意先关闭输出流,再关闭输入流
if (out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

阅读全文

与filecopyjava相关的资料

热点内容
哪个app可以卖二手课程 浏览:474
互联网app如何算毛利 浏览:300
excel文件处理插件 浏览:666
在电脑上怎么找不到微信文件夹 浏览:116
u盘打开后有文件没内容 浏览:210
编程怎么输出逗号 浏览:421
微信玩红包怎么定大小 浏览:825
电脑病毒测试代码 浏览:118
得物app为什么总是更新 浏览:965
银企对账程序 浏览:164
r读取excel文件 浏览:363
上古卷轴5控制台附魔代码 浏览:514
缓存文件合并找不到文件 浏览:871
桌面保存一下文件找不到 浏览:645
程序美工标准 浏览:191
漂流瓶的文件在哪里 浏览:319
数据的正负偏差怎么计算 浏览:242
文件名用不用带TXT 浏览:968
小米十数据线是哪个 浏览:463
caddws文件 浏览:962

友情链接