2017-04-12 44 views
0

我目前正在嘗試從android應用程序的根目錄讀取內容。我實現所有的權限在我的表現爲如下陳述:Android:從根應用程序文件夾讀取內容。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

和我的代碼:

public void copytoFileDestination(){ 

    //get the root path of the application. 
    String rootPath = getFilesDir().getPath() + "/images/"; 
    File destination = new File(rootPath); 

    String imgPath = "/storage/emulated/0/Pictures/somefilename.jpg" 
    File source = new File(imgPath); 

    try{ 
     //copy source location to destination directory 
     copyFile(source, destination); 

     //display all the contents of rootPath! How? Attempt: 
     File[] files = destination.listFiles(); 
     for (int i = 0; i < files.length; i++) 
     { 
      Log.d("Files", "FileName:" + files[i].getName()); 
     } 

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

    private void copyFile(File sourceFile, File destFile) throws IOException { 
    if (!sourceFile.exists()) { 
     return; 
    } 

    FileChannel source = null; 
    FileChannel destination = null; 
    source = new FileInputStream(sourceFile).getChannel(); 
    destination = new FileOutputStream(destFile).getChannel(); 
    if (destination != null && source != null) { 
     destination.transferFrom(source, 0, source.size()); 
     Log.d("copy file", "complete"); 
    } 
    if (source != null) { 
     source.close(); 
    } 
    if (destination != null) { 
     destination.close(); 
    } 

} 

我從源(圖像路徑)只是想複製到目的地(根路徑)然後顯示目的地的內容。然而,我在files.length得到一個空的異常,這意味着目標文件包含...沒有文件?是因爲我無法從目標目錄讀取嗎?

有人能夠啓發我嗎?

順便說一句:

  • destination.exist()是正確的。
  • destination.canRead()爲true。

幫忙!

回答

0

試試這個,我對我的作品,

public static void copyFile(File sourceFile, File destFile) throws IOException { 
    if (!sourceFile.exists()) { 
     return; 
    } 

    FileChannel source = null; 
    FileChannel destination = null; 
    source = new FileInputStream(sourceFile).getChannel(); 
    destination = new FileOutputStream(destFile).getChannel(); 
    byte[] var1 = new byte[1024]; 

    int var2; 
    while((var2 = source.read(var1)) > 0) { 
     destination.write(var1, 0, var2); 
    } 

    source.close(); 
    destination.close(); 
} 
相關問題