2017-02-06 37 views
0

我正在使用下面的代碼在Android中移動文件。在Android中移動文件時出錯

public static void moveFile(String inputPath, String inputFile, String outputPath, String absolutePath) { 

    InputStream in = null; 
    OutputStream out = null; 

    try { 

     //create output directory if it doesn't exist 
     File dir = new File (outputPath); 
     if (!dir.exists()) 
     { 
      dir.mkdirs(); 
     } 


     in = new FileInputStream(inputPath + inputFile); 
     out = new FileOutputStream(outputPath + inputFile); 

     byte[] buffer = new byte[1024]; 
     int read; 
     while ((read = in.read(buffer)) != -1) { 
      out.write(buffer, 0, read); 
     } 
     in.close(); 
     in = null; 

     // write the output file 
     out.flush(); 
     out.close(); 
     out = null; 

     // delete the original file 
     new File(absolutePath).delete(); 


    } 

    catch (FileNotFoundException fnfe1) { 
     Log.e("Moving file not found", fnfe1.getMessage()); 
    } 
    catch (Exception e) { 
     Log.e("While Moving", e.getMessage()); 
    } 

但大多數的時候,它表明了我的錯誤,如下圖所示:

移動找不到文件:/call_14-43-46_IN_+919737276726.amr(只讀文件系統)

我已選中並且要移動的文件是普通文件,因爲它是由呼叫記錄器記錄而不是隻讀的。 請幫忙。

+0

告訴你如何調用這個函數。顯示參數的值。 – greenapps

+0

'dir.mkdirs();'。檢查返回值,因爲它可能無法創建目錄。在這種情況下,向用戶表示敬酒。並返回。不要繼續,因爲嘗試在不存在的目錄中創建文件是沒有意義的。 – greenapps

回答

0

在android中,您無法直接訪問根目錄(/),它以只讀方式掛載。檢查你的路徑,你不應該試圖寫或讀/反正。

+0

我沒有訪問根路徑,並且源和目標路徑都位於外部存儲器中。我編輯了這個問題。 –

0

您需要問問自己,您的文件是否應該可用於「外部」世界,或者只是您的程序本身需要。根據該決定,您有幾個選項:

實例Context(例如Activity)知道openFileOutputopenFileInput。兩者都返回流,並且可以在沒有進一步權限的情況下使用,但將文件存儲在應用程序專用的位置。

如果您只需要臨時提供文件,請考慮Context.getCacheDir。或者,Java方式:File.createTempFile。另一種值得研究的方法是Context.getExternalFilesDir

一個側面說明:不是膠合在一起,你的路徑手動我建議使用新File("path", "dir").getAbsolutePath