java Android 将文本文件写入内部存储
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34658903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android write text file to internal storage
提问by FAZ
Using emulator I am able to write a text file to /data/local but when I use my device, for the same path /data/local I get Permission denied. Could anyone tell me which path of Internal Storage is read-write and I can write my file there. It would be better if I could achieve this without rooting my device.
使用模拟器我可以将文本文件写入 /data/local 但是当我使用我的设备时,对于相同的路径 /data/local 我得到权限被拒绝。谁能告诉我内部存储的哪个路径是读写的,我可以在那里写我的文件。如果我可以在不生根我的设备的情况下实现这一点会更好。
回答by Andrew Brooke
Take a look at this guidefrom the Android docs.
从 Android 文档中查看本指南。
Calling getFilesDir
will return a File
object for your app's internal directory.
调用getFilesDir
将为File
您的应用程序的内部目录返回一个对象。
You can use that to write a new file in the directory like this
您可以使用它在目录中写入一个新文件,如下所示
File file = new File(context.getFilesDir(), fileName);
Here's an answer with an example of how to write text to a file using getFilesDir
: https://stackoverflow.com/a/9306962/2278598
这是一个如何使用以下示例将文本写入文件的答案getFilesDir
:https: //stackoverflow.com/a/9306962/2278598
Or, you can use openFileOutput
, like this
或者,您可以openFileOutput
像这样使用
String fileName = "yourFileName";
String textToWrite = "This is some text!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName , Context.MODE_PRIVATE);
outputStream.write(textToWrite.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
回答by webo80
Android apps are isolated one to another, so your app has a dedicated folder in internal storage to read/write into it.
Android 应用程序彼此隔离,因此您的应用程序在内部存储中有一个专用文件夹,可以对其进行读/写。
You can access it via
您可以通过
File path = Environment.getDataDirectory();
As it vary between devices.
因为它因设备而异。
Outside the app (e.g. from a shell, or a file explorer) you can't even read private data folders of the apps, you need a rooted device (as the emulator) to do it. If you want a file to be world-readable, put it in the external storage.
在应用程序之外(例如从外壳或文件浏览器),您甚至无法读取应用程序的私有数据文件夹,您需要有根设备(作为模拟器)来执行此操作。如果您希望文件是世界可读的,请将其放在外部存储中。