如何通过您的应用程序访问另一个应用程序的/data文件夹? [英] How to access /data folder of another application through your application?
问题描述
有一个应用程序生成的文本文件,我想将该文件读取为应用程序中的字符串.我将如何实现这一目标,我们将不胜感激.这两个应用程序都是我的应用程序,因此我可以获得权限.
there is a text file that an application produces, I would like to take that file and read it as strings in my application. How can I achieve that, any help would be grateful. Both applications are my applications so I can get the permissions.
谢谢!
推荐答案
使用标准的android-storage可以实现,其中也存储了所有用户文件:
This is possible using the standard android-storage, where all the user's files are stored too:
您需要做的就是在两个应用程序中访问相同的文件和相同的路径,例如:
All you need to do is to access the same file and the same path in both applications, so e.g.:
String fileName = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/myFileNameForBothApplications.txt";
其中 myFolderForBothApplications 和 myFileNameForBothApplications 可以替换为您的文件夹/文件名,但这必须是在两个应用程序中都使用相同的名称.
Where myFolderForBothApplications and myFileNameForBothApplications can be replaced by your folder/filename, but this needs to be the same name in both applications.
Environment.getExternalStorageDirectory() 将文件对象返回到设备的公用文件目录,用户也可以看到相同的文件夹. 通过调用getPath()方法,将返回表示此存储路径的字符串,因此您可以在以后添加文件夹/文件名.
Environment.getExternalStorageDirectory() returns a File-Object to the common, usable file-directory of the device, the same folder the user can see too. By calling the getPath() method, a String representing the path to this storage is returned, so you can add your folder/filenames afterwards.
因此,完整的代码示例为:
So a full code example would be:
String path = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/";
String pathWithFile = path + "myFileNameForBothApplications.txt";
File dir = new File(path);
if(!dir.exists()) { //If the directory is not created yet
if(!dir.mkdirs()) { //try to create the directories to the given path, the method returns false if the directories could not be created
//Make some error-output here
return;
}
}
File file = new File(pathWithFile);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
//File couldn't be created
return;
}
此后,您可以根据提供的内容写入文件或从文件中读取内容,例如在此答案中.
Afterwards, you can write in the file or read from the file as provided e.g. in this answer.
请注意,这样存储的文件对用户可见,并且我可以由用户对其进行编辑/删除.
Note that the file stored like this is visible for the user and my be edited / deleted by the user.
还要注意getExternalStorageDirectory()的JavaDoc是怎么说的:
Also note what the JavaDoc for the getExternalStorageDirectory() says:
返回主外部存储目录.如果用户已将其安装在计算机上,已从设备中删除或发生了其他一些问题,则该目录当前可能无法访问.您可以使用getExternalStorageState()确定其当前状态.
我不知道这是否是解决问题的最好/最安全的方法,但是应该可以.
I do not know if this is the best/safest way to fix your problem, but it should work.
这篇关于如何通过您的应用程序访问另一个应用程序的/data文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!