我寫了一個方法,它創建一個文件並將數據寫入文件並存儲在內部存儲器中。當我得到文件的絕對路徑或路徑時[我已經添加了日誌消息來試驗文件上的操作],它顯示出該文件正在創建在根目錄下,並在/ data/data/mypackagename下創建/files/filename.txt。不過,我可以在DDMS上找到這些文件夾,在那裏我可以找到由我寫的方法創建的文件。但我無法打開該文件,因爲我沒有權限。如何將文件寫入Android內部存儲的文件夾?
當我看着我的Android設備,我找不到這些目錄。我查了一下堆棧溢出,有些人回答說內部存儲器中的/ data/data文件夾是隱藏的,要訪問它們,我必須爲我不想做的設備創建根目錄。
下一個方法:在Android設備上有一個名爲MyFiles的文件夾[我正在使用運行Android 4.4的Galaxy Tab 4進行測試]。在這個文件夾下有Device Storage目錄,其中包含文件,圖片,音樂,鈴聲,Android等各種文件夾。因此,相機,電子表格應用程序等應用程序能夠將圖片寫入或保存到圖片文件夾或文檔文件夾中的txt文件。同樣,我怎樣才能將我在函數中創建的文件寫入Documents文件夾或任何其他可通過設備訪問的文件夾。請幫助我如何做到這一點,任何幫助表示讚賞。
以下是我寫的代碼:
public void addLog(String power_level){
// creates a logFile in the root directory of the internal storage of the application.
// If the file does not exists, then it is created.
Log.d("AppendPower", "In addLog method");
//File logFile = new File(((Context)this).getFilesDir(), "logFile.txt");
File logFile = new File(getFilesDir(), "logFile.txt");
Log.d("FilesDir Path", getFilesDir().getAbsolutePath());
Log.d("FilesDir Name", getFilesDir().getName());
Log.d("Path on Android", logFile.getPath());
Log.d("Absolute Path on Android", logFile.getAbsolutePath());
Log.d("Parent", logFile.getParent());
if(!logFile.exists()){
try{
logFile.createNewFile();
}catch(IOException io){
io.printStackTrace();
}
}
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
writer.write("Battery level reading");
writer.append(power_level);
Log.d("Power_Level in try", power_level);
writer.newLine();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
非常感謝。它工作完美。 – ShellZero