我有寫範例程式碼,附上超連結:

https://github.com/DeyuGoGo/AndroidBloger/blob/master/app/src/main/java/go/deyu/androidbloger/CopyActivity.java

還要記得在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());

           }

       }

 

 

 

arrow
arrow
    全站熱搜

    Deyu 發表在 痞客邦 留言(3) 人氣()