尚學堂 JAVA300集 第十章IO技術 video173 IO_標準步驟---拓展:copy 資料夾及資料夾下內容到目標資料夾下
阿新 • • 發佈:2018-12-11
video173 IO_標準步驟—拓展:copy 資料夾及資料夾下內容到目標資料夾下
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* copy 該資料夾及資料夾下內容到目標資料夾下
* @author lei.ai
*
*/
public class IOCopy03extend {
public static void main(String[] args) throws IOException {
copytodir("D:\\code\\Pro10\\test","D:\\code\\Pro10\\copytest");
}
private static void copytodir(String sourcepath,String destpath) throws IOException {
// TODO Auto-generated method stub
File sorce = new File(sourcepath); //原始檔
File dest = new File(destpath);
//建立目標資料夾
dest.mkdirs(); //如果目標資料夾已存在,則建立失敗
//將原始檔名與目標路徑相結合,存到buffd中
File buffd = new File(dest.getAbsolutePath(),sorce.getName());
if (sorce!=null && sorce.exists()) {
if (sorce.isFile()) { //如果是檔案,在目標目錄中建立該檔案,並將內容複製
buffd.createNewFile();
copyfile(sorce.getAbsolutePath(), buffd.getAbsolutePath());
}else { //如果是資料夾,則遞迴呼叫
for(File s:sorce.listFiles()) {
File buffs = new File(sorce.getAbsolutePath(),s.getName());
copytodir(buffs.getAbsolutePath(),buffd.getAbsolutePath());
}
}
}
}
private static void copyfile(String sourcepath,String destpath) {
//1.建立源
File sorce = new File(sourcepath); //原始檔
File dest = new File(destpath); //目標檔案
//2.選擇流
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(sorce);
os = new FileOutputStream(dest);
//3.操作
//分段讀取
byte[] flush = new byte[1024];
int len; //定義解碼接收長度
while ((len=is.read(flush))!=-1) {
os.write(flush, 0, len);
/*
String st = new String(flush, 0, len); //編碼
byte[] temp = st.getBytes(); //解碼
os.write(temp, 0, temp.length); //寫入
*/
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally { //4、釋放資源 分別關閉 先開啟的後關閉
if (os!=null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(is!=null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}