小編給大家分享一下java如何將一個目錄下的所有數據復制到另一個目錄下,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
具體內容如下
/*
將"C:\\JavaProducts\\Source"下的所有數據復制到"C:\\Target"下
*/
import java.io.*;
public class JavaCopyDemo{
final static String SOURCESTRING = "C:\\JavaProducts\\Source";
final static String TARGETSTRING = "C:\\Target";
public static void main(String[] args){
if(!(new File(SOURCESTRING)).exists()){
System.out.println("源文件" + SOURCESTRING + "不存在,無法復制!");
return;
}else if((new File(TARGETSTRING)).exists()){
System.out.println("目標文件" + TARGETSTRING + "已經存在,無法復制!");
return;
}else{
if((new File(SOURCESTRING)).isFile()){
copyFile(new File(SOURCESTRING),new File(TARGETSTRING));
}else if((new File(SOURCESTRING)).isDirectory()){
copyDirectory(SOURCESTRING,TARGETSTRING);
}
}
}
private static void copyFile(File sourceFile,File targetFile){
if(!sourceFile.canRead()){
System.out.println("源文件" + sourceFile.getAbsolutePath() + "不可讀,無法復制!");
return;
}else{
System.out.println("開始復制文件" + sourceFile.getAbsolutePath() + "到" + targetFile.getAbsolutePath());
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try{
fis = new FileInputStream(sourceFile);
bis = new BufferedInputStream(fis);
fos = new FileOutputStream(targetFile);
bos = new BufferedOutputStream(fos);
int len = 0;
while((len = bis.read()) != -1){
bos.write(len);
}
bos.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(fis != null){
fis.close();
}
if(bis != null){
bis.close();
}
if(fos != null){
fos.close();
}
if(bos != null){
bos.close();
}
System.out.println("文件" + sourceFile.getAbsolutePath() + "復制到" + targetFile.getAbsolutePath() + "完成");
}catch(IOException e){
e.printStackTrace();
}
}
}
}
private static void copyDirectory(String sourcePathString,String targetPathString){
if(!new File(sourcePathString).canRead()){
System.out.println("源文件夾" + sourcePathString + "不可讀,無法復制!");
return;
}else{
(new File(targetPathString)).mkdirs();
System.out.println("開始復制文件夾" + sourcePathString + "到" + targetPathString);
File[] files = new File(sourcePathString).listFiles();
for(int i = 0; i < files.length; i++){
if(files[i].isFile()){
copyFile(new File(sourcePathString + File.separator + files[i].getName()),new File(targetPathString + File.separator + files[i].getName()));
}else if(files[i].isDirectory()){
copyDirectory(sourcePathString + File.separator + files[i].getName(),targetPathString + File.separator + files[i].getName());
}
}
System.out.println("復制文件夾" + sourcePathString + "到" + targetPathString + "結束");
}
}
}以上是“java如何將一個目錄下的所有數據復制到另一個目錄下”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。