简体   繁体   English

Android将文本文件写入内部存储

[英]Android write text file to internal storage

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. 使用模拟器,我可以将文本文件写入/ data / local,但是当我使用设备时,对于/ data / local相同的路径,我将获得“权限被拒绝”。 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. 如果我无需植根设备就可以做到这一点,那就更好了。

Take a look at this guide from 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 : getFilesDir

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();
}

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 (eg 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. 如果您想让某个文件具有世界范围的可读性,请将其放入外部存储中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM