我有寫範例程式碼,附上超連結:
還要記得在Manifest中宣告要讀寫檔案的權限,加入這兩行:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public void copyDownLoadDir(){
// 複製Download資料夾
String DownloadDirPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
GoCopyFolder(DownloadDirPath , DownloadDirPath+"testCopyDir");
}
// 單一檔案的複製齁,comePath輸入想要複製的檔案路徑,goPath是目的地路徑拉
public void GoCopyFile(String comepath, String gopath) throws IOException {
try {
File wantfile = new File(comepath);
File newfile = new File(gopath);
InputStream in = new FileInputStream(wantfile);
OutputStream out = new FileOutputStream(newfile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (Exception e) {
Log.e("copy file error", e.toString());
// TODO: handle exception
}
}
// 整個資料夾的複製齁,comePath輸入想要複製的資料夾路徑,goPath是目的地路徑拉
public void GoCopyFolder(String comePath, String goPath){
try {
( new File(goPath)).mkdirs(); //弄資料夾拉
File a= new File(comePath);
String[] file=a.list();
File temp= null ;
for ( int i = 0 ; i < file.length; i++) {
if (comePath.endsWith(File.separator)){
temp= new File(comePath+file[i]);
}
else
{
temp= new File(comePath+File.separator+file[i]);
}
if (temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(goPath + "/" +
(temp.getName()).toString());
byte [] b = new byte [1024];
int len;
while ( (len = input.read(b)) != - 1 ) {
output.write(b, 0 , len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()){
//裡面還有東西要繼續幹
GoCopyFolder(comePath+ "/" +file[i],goPath+ "/" +file[i]);
}
}
}
catch (Exception e) {
Log.e("folder error", e.toString());
}
}

請問 public void copy(String comePath,String goPath) {..} 中,他說沒有找到copy()這個動作 已經嘗試用 public void copy(String comePath,String goPath,View v) {..} 但是一樣找不到
聽起來是方法名稱不同造成的,我範例貼的方法名稱是:GoCopyFolder ,你要把下面呼叫GoCopyFolder的方法也改成你的copy應該就可以了,如果還是不行你可以貼程式碼給我 我幫你改XDD
使用 GoCopyFolder 到 FileOutStream時,Log就出現E/folder error: java.io.FileNotFoundException: /storage/emulated/0HTDB/KJDB01.db: open failed: ENOENT (No such file or directory) 為甚麼會開啟錯誤?
我想到一個可能的原因,你的Manifest 檔案要宣告兩個權限: uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 我今天有寫一個測試去複製下載資料夾,成功複製。 我測試的一行代碼如下:GoCopyFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+"testCopyDir"); 你再看一下XDD
我找到原因了~我的路徑少打一個"/",你的方法ˋ真的很實用~ 謝謝分享喔^^
問題有找到原因就好!讚唷!