我编写了一个创建文件并将数据写入文件并存储在内部存储器中的方法。当我获得文件的绝对路径或路径 [我已添加日志消息以试验对文件的操作] 时,它显示该文件正在根目录下创建,并且在 /data/data/mypackagename 下/文件/文件名.txt。不过,我可以在 DDMS 上找到这些文件夹,在那里我可以找到由我编写的方法创建的文件。但我也无法打开该文件,因为我没有权限。
当我查看我的 Android 设备时,我找不到这些目录。我查看了堆栈溢出,有些人回答说内部存储中的 /data/data 文件夹是隐藏的,要访问它们,我必须根植我不想做的设备。
下一个方法:在 android 设备上有一个名为 MyFiles 的文件夹[我正在使用运行 Android 4.4 的 Galaxy Tab 4 进行测试]。在此文件夹下有 Device Storage 目录,其中包含各种文件夹,如 Documents、Pictures、Music、Ringtones、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();
}
}