简体   繁体   English

无法将文本文件写入 Android 中的文档文件夹

[英]Can't write text files to documents folder in Android

I have an app that I am trying to write temperature values from my thermal camera to a text file.我有一个应用程序,我正在尝试将热像仪中的温度值写入文本文件。

Yesterday, I was able to solve this issue: How to write and constantly update a text file in Android , although after re-installing I am no longer able to write files to documents directory.昨天,我能够解决这个问题: 如何在 Android 中编写并不断更新文本文件,尽管重新安装后我不再能够将文件写入文档目录。

I am getting the following exception:我收到以下异常:

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Documents/1658486312697.txt: open failed: EPERM (Operation not permitted) W/System.err:java.io.FileNotFoundException:/storage/emulated/0/Documents/1658486312697.txt:打开失败:EPERM(不允许操作)

Writting code:编写代码:

long time = System.currentTimeMillis();
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
try {
    File outFile1 = new File(path+"/"+String.valueOf(time)+".txt");
    Log.e("outFile1:", outFile1.getAbsolutePath());
    Writer out = new BufferedWriter(new OutputStreamWriter(
                                 new FileOutputStream(outFile1,true), "utf-8"), 10240);
    for (int i = 10; i < 384*288+10; i++) {
        out.write(temperature1[i] + "\r\n");
    }
    out.flush();
    out.close();
} catch (Exception e){
    e.printStackTrace();
}

Permissions on AndroidManifest.xml : AndroidManifest.xml上的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

I am currently testing on Android 12 device I'd like to know why can I not save my text files to documents and what needs to be done to save it the right way.我目前正在 Android 12 设备上进行测试,我想知道为什么我不能将我的文本文件保存到文档中,以及需要做些什么才能以正确的方式保存它。

It's because outFile1 doesn't exist.这是因为 outFile1 不存在。

File outFile1 = new File(path+"/"+String.valueOf(time)+".txt");
outFile1.createNewFile(); //add this line

And make sure you have allowed MANAGE_EXTERNAL_STORAGE permission in Application Setting.并确保您已在应用程序设置中允许 MANAGE_EXTERNAL_STORAGE 权限。 read more here 在这里阅读更多

And also for below android 11 devices you have to ask for WRITE_EXTERNAL_STORAGE permission using "Permission Dialog".而且对于低于 android 11 的设备,您必须使用“权限对话框”请求 WRITE_EXTERNAL_STORAGE 权限。 read more here 在这里阅读更多

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

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