2016-05-02 137 views
0

我需要將文件從一個地方複製到另一個地方。我已經找到了很好的解決方案:如何一次性複製Android中的文件?不創建數十行代碼!像在樣本中一樣,

import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 

public class FileCopyTest { 
public static void main(String[] args) { 
    Path source = Paths.get("/Users/apple/Desktop/test.rtf"); 
    Path destination = Paths.get("/Users/apple/Desktop/copied.rtf"); 

    try { 
     Files.copy(source, destination); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
} 

這個庫的工作不錯,但不提供的Android ...

我試圖找出我應該使用,而不是哪一種方式,但它的任何建議。 ..我幾乎可以肯定它應該是一個允許一次性複製文件的庫。

如果有人知道說請,我相信這將是非常有幫助的答案負載的人。

謝謝!

+0

的可能的複製[如何以編程方式移動,複製和SD刪除文件和目錄?(http://stackoverflow.com/questions/4178168/how-to -programmatically-move-copy-and-delete-files-and-directories-on-sd) –

+0

如果你只想鏈接到一個庫來爲你做這件事,那麼這對Stack Overflow來說不是一個合適的問題。 –

+0

@MikeM。我編輯標題 –

回答

0

很好用commons-io,你可以做到這一點

FileInputStream source = null; 
FileOutputStream destination = null; 
try { 
    source = new FileInputStream(new File(/*...*/)); 
    destination = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), /*...*/); 
    IOUtils.copy(source, destination); 
} finally { 
    IOUtils.closeQuietly(source); 
    IOUtils.closeQuietly(destination); 
} 

只需添加

compile 'org.apache.directory.studio:org.apache.commons.io:2.4' 

到的build.gradle文件

+0

但'IOUtils'在Android中不可用... –

+0

你是什麼意思**在Android **中不可用?將它添加到您的build.gradle相關性中。如果你想使用默認的類,顯然不是一個庫,儘管你在你的初始文章中聲明瞭什麼,那麼只要做了'commons-io'就可以做到。 – EpicPandaForce

+0

好的,對不起。同意你 –

0

試試這個代碼

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.nio.channels.FileChannel; 
public class CopyFile { 

public static void main(String[] args) { 
    File sourceFile = new File(
      "/Users/Neel/Documents/Workspace/file1.txt"); 

    File destFile = new File(
      "/Users/Neel/Documents/Workspace/file2.txt"); 

    /* verify whether file exist in source location */ 
    if (!sourceFile.exists()) { 
     System.out.println("Source File Not Found!"); 
    } 

    /* if file not exist then create one */ 
    if (!destFile.exists()) { 
     try { 
      destFile.createNewFile(); 

      System.out.println("Destination file doesn't exist. Creating 

    one!"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    FileChannel source = null; 
    FileChannel destination = null; 

    try { 

     /** 
     * getChannel() returns unique FileChannel object associated a file 
     * output stream. 
     */ 
     source = new FileInputStream(sourceFile).getChannel(); 

     destination = new FileOutputStream(destFile).getChannel(); 

     if (destination != null && source != null) { 
      destination.transferFrom(source, 0, source.size()); 
     } 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    finally { 
     if (source != null) { 
      try { 
       source.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     if (destination != null) { 
      try { 
       destination.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    } 
    } 
-1

使用這個工具類讀/寫文件的SD卡:

public class MyFile { 

    String TAG = "MyFile"; 
    Context context; 
    public MyFile(Context context){ 
     this.context = context; 
    } 

    public Boolean writeToSD(String text){ 
     Boolean write_successful = false; 
     File root=null; 
      try { 
       // check for SDcard 
       root = Environment.getExternalStorageDirectory(); 
       Log.i(TAG,"path.." +root.getAbsolutePath()); 

       //check sdcard permission 
       if (root.canWrite()){ 
        File fileDir = new File(root.getAbsolutePath()); 
        fileDir.mkdirs(); 

        File file= new File(fileDir, "samplefile.txt"); 
        FileWriter filewriter = new FileWriter(file); 
        BufferedWriter out = new BufferedWriter(filewriter); 
        out.write(text); 
        out.close(); 
        write_successful = true; 
       } 
      } catch (IOException e) { 
       Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage()); 
       write_successful = false; 
      } 
     return write_successful; 
    } 

    public String readFromSD(){ 
     File sdcard = Environment.getExternalStorageDirectory(); 
     File file = new File(sdcard,"samplefile.txt"); 
     StringBuilder text = new StringBuilder(); 
     try { 
      BufferedReader br = new BufferedReader(new FileReader(file)); 
      String line; 
      while ((line = br.readLine()) != null) { 
       text.append(line); 
       text.append('\n'); 
      } 
     } 
     catch (IOException e) { 
     } 
     return text.toString(); 
    } 

    @SuppressLint("WorldReadableFiles") 
    @SuppressWarnings("static-access") 
    public Boolean writeToSandBox(String text){ 
     Boolean write_successful = false; 
     try{ 
      FileOutputStream fOut = context.openFileOutput("samplefile.txt", 
        context.MODE_WORLD_READABLE); 
      OutputStreamWriter osw = new OutputStreamWriter(fOut); 
      osw.write(text); 
      osw.flush(); 
      osw.close(); 
     }catch(Exception e){ 
      write_successful = false; 
     } 
     return write_successful; 
    } 
    public String readFromSandBox(){ 
     String str =""; 
     String new_str = ""; 
     try{ 
      FileInputStream fIn = context.openFileInput("samplefile.txt"); 
      InputStreamReader isr = new InputStreamReader(fIn); 
      BufferedReader br=new BufferedReader(isr); 

      while((str=br.readLine())!=null) 
      { 
       new_str +=str; 
       System.out.println(new_str); 
      }    
     }catch(Exception e) 
     {   
     } 
     return new_str; 
    } 
} 

注意,你應該給在AndroidManifest文件此權限。

這裏permision

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 

欲瞭解更多詳情請訪問:http://www.coderzheaven.com/2012/09/06/read-write-files-sdcard-application-sandbox-android-complete-example/

Android developer official Docs

+0

Downvote是因爲'close()'在'try {'中,而不是在'finally {'中。 – EpicPandaForce

相關問題