2014-11-24 67 views
1

上,我想我的應用程序創建的SD卡上的文件夾和文件保存在裏面。這就是我現在所需要的,只是將它保存在我的應用程序數據中。如何將文件保存到特定地點的電話

File file = new File(context.getExternalFilesDir(""), fileName);   

    FileOutputStream os = null; 

    try { 
     os = new FileOutputStream(file); 
     wb.write(os); 
     Log.w("FileUtils", "Writing file" + file); 
     success = true; 
    } catch (IOException e) { 
     Log.w("FileUtils", "Error writing " + file, e); 
    } catch (Exception e) { 
     Log.w("FileUtils", "Failed to save file", e); 
    } finally { 
     try { 
      if (null != os) 
       os.close(); 
     } catch (Exception ex) { 
     } 
    } 

我該怎麼做?

好了,所以我做了這個。我是否做對了?

String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + ""; 
    File file = new File(fullPath); 
     if (!file.exists()) { 
      file.mkdirs(); 
     } 


    FileOutputStream os = null; 

    try { 
     os = new FileOutputStream(file); 
     wb.write(os); 
     Log.w("FileUtils", "Writing file" + file); 
     success = true; 
    } catch (IOException e) { 
     Log.w("FileUtils", "Error writing " + file, e); 
    } catch (Exception e) { 
     Log.w("FileUtils", "Failed to save file", e); 
    } finally { 
     try { 
      if (null != os) 
       os.close(); 
     } catch (Exception ex) { 
     } 
    } 
+0

它的文件夾比這更簡單,看我的更新來回答你的更新。 – weston 2014-11-24 07:58:43

回答

1

您最好的選擇是使用Environment.getExternalStorageDirectory()來查找要使用的根路徑。

但是,請注意,這不是nessasarily SD卡,從docs:

注意:不要用這個詞混淆「外部」在這裏。這個目錄可以更好地被認爲是媒體/共享存儲。它是一個文件系統,可以容納大量的數據並在所有應用程序之間共享(不強制執行權限)。傳統上這是一張SD卡,但它也可以實現爲與受保護的內部存儲器不同的設備中的內置存儲器,並且可以作爲文件系統安裝在計算機上。

例子,只是改變你的第一行是:

File file = new File(Environment.getExternalStorageDirectory(), fileName); 

需要有一個目錄?:

File dir = new File(Environment.getExternalStorageDirectory(), "yourdir"); 
dir.mkDirs(); 
File file = new File(dir, fileName); 
+0

感謝兄弟! – dtrodriguez 2014-11-24 08:04:05

0

試試這個,像這樣創建

String fullPath = Environment.getExternalStorageDirectory() 
      .getAbsolutePath() + "/Foldername"; 
File dir = new File(fullPath); 
     if (!dir.exists()) { 
      dir.mkdirs(); 
     } 
相關問題