1. 程式人生 > >複製一個資料夾下所有檔案(包括子資料夾)並修改檔案字尾名 java實現加密文件unlock

複製一個資料夾下所有檔案(包括子資料夾)並修改檔案字尾名 java實現加密文件unlock

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class ceshi {

public  File originFile;
public  File targetFile;

public ceshi(){};
public ceshi(String origin,String target){
this.originFile=new File(origin);
this.targetFile=new File(target);
}

//copy資料夾並copy檔案
public  void copyAll(File file){
//得到origin資料夾所有file
File[] fileList=file.listFiles();
for(File f:fileList){
//得到copy原始檔路徑
String from =f.getAbsolutePath();

//得到輸出資料夾路徑
String to=from.replace(originFile.getAbsolutePath(), targetFile.getAbsolutePath());

if(f.isDirectory()){
File toDir=new File(to);
toDir.mkdirs();
copyAll(f);
}else{
//建立輸出資料夾
int a=to.lastIndexOf("\\");
String toPath=to.substring(0,a);
File toDir=new File(toPath);
toDir.mkdirs();

//修改檔案字尾名doc=wow;xls=lol;ppt=dnf;pdf=threekindom
if(to.substring(to.lastIndexOf(".")+1).equals("doc") || to.substring(to.lastIndexOf(".")+1).equals("docx")){
to=to.substring(0, to.lastIndexOf("."))+".wow";
}else if(to.substring(to.lastIndexOf(".")+1).equals("xls") || to.substring(to.lastIndexOf(".")+1).equals("xlsx")){
to=to.substring(0, to.lastIndexOf("."))+".lol";
}else if(to.substring(to.lastIndexOf(".")+1).equals("ppt") || to.substring(to.lastIndexOf(".")+1).equals("pptx")){
to=to.substring(0, to.lastIndexOf("."))+".dnf";
}else if(to.substring(to.lastIndexOf(".")+1).equals("pdf")){
to=to.substring(0, to.lastIndexOf("."))+".threekindom";
}
else{
to=to.substring(0, to.lastIndexOf("."))+".games";
}

//複製檔案迭代
copyFile(from, to);
}
}

}

//封裝好的 copy檔案的方法
public  void copyFile(String from,String to){
InputStream in=null;
OutputStream out=null;

try {
in=new FileInputStream(from);
out=new FileOutputStream(to);
byte[] arr=new byte[1024];
int i=0;
while((i=in.read(arr))!=-1){
out.write(arr,0,i);
};

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

public static void main(String [] args){

ceshi c=new ceshi("d:\\lock","d:\\unlock");
c.copyAll(c.originFile);

}