简体   繁体   English

无法写入文件 - 为什么?

[英]Unable to write to file - why?

I am attempting to save to long term file storage in android as well as create a new file in the process.我正在尝试保存到 android 中的长期文件存储,并在此过程中创建一个新文件。 This code keeps crashing with minimal helpful logcat.此代码不断崩溃,并使用最少的有用 logcat。

Thanks.谢谢。

public void save (String text) {
    FileOutputStream fos = null;
    try {
        fos = openFileOutput("logfile.txt", MODE_PRIVATE);
        fos.write(text.getBytes());
    } catch (FileNotFoundException e)
    {} catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fos != null)
        {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

I expect it to create a file called logfile.txt and print text to it but instead it crashes.我希望它创建一个名为 logfile.txt 的文件并向其打印文本,但它却崩溃了。

You need the file write permission in the manifest and ask for it (again) during runtime (as a pop-up).您需要清单中的文件写入权限,并在运行时(作为弹出窗口)(再次)请求它。 This is assuming you use external storage.这是假设您使用外部存储。 Did you do this?你做了这个了吗?

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
if (ContextCompat.checkSelfPermission(getActivity(),  Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x11);
                    } else Log.d("TAG", "permission already granted");

Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:尝试类似的方法,以便从 tmp / 私有存储中的File中获取FileOutputStream

// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);

The resulting path should be /data/data/tld.domain.package/files/logfile.txt .结果路径应该是/data/data/tld.domain.package/files/logfile.txt

file.getAbsolutePath() has the value. file.getAbsolutePath()具有值。

See Save a file on internal storage .请参阅在内部存储上保存文件

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

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