我编写了一个方法,它创建一个文件并将数据写入文件并存储在内部存储中。当我获取文件的绝对路径或路径时[我添加了日志消息以尝试在文件上执行操作],它显示该文件正在根目录下创建,并且在/data/data/mypackagename/files/filename.txt下。尽管如此,我可以在DDMS上找到这些文件夹,我可以找到由我编写的方法创建的文件。但是我无法打开该文件,因为我没有权限。
当我查看我的Android设备时,找不到这些目录。我在stackoverflow上搜索,有些人回答说内部存储中的/data/data文件夹是隐藏的,要访问它们,我必须root设备,但我不想这样做。
下一步方法:android设备中有一个名为MyFiles的文件夹[我使用运行Android 4.4的Galaxy Tab 4进行测试]。在这个文件夹下有一个Device Storage文件夹,其中包含各种文件夹,例如Documents、Pictures、Music、Ringtones、Android等等。因此,像相机、电子表格应用程序这样的应用程序能够将图片保存到pictures文件夹或在documents文件夹中保存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();
}
}
/sdcard/
可以工作。它通常指的是“内置”的SD卡,其实并不是真正的SD卡,但为了兼容性而存在。如果你的Java代码写入/sdcard/
,而adb pull
从同样的/sdcard/
读取,无论是否是真正的SD卡都没有问题。 - 18446744073709551615