㈠ 在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();
}
}
}
}