Android: Asus Nexus 7 does not commit emulated memory until restart

亡梦爱人 提交于 2020-01-05 03:39:09

问题


I have a very specific issue - I am trying to write to external storage on an Asus Nexus 7, but it is writing to the emulated directory on the device.

Here is the code I am using:

public static void writeExternalMedia(Context context) {
    if(isExternalStorageWritable()) {
        String content = "hello world";

        File filedir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/test");
        filedir.mkdir();

        File file;

        FileOutputStream outputStream;

        try {
            file = new File(filedir, "test.txt");

            if (!file.exists()) {
                file.createNewFile();
            }

            outputStream = new FileOutputStream(file);
            outputStream.write(content.getBytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

Whenever I restart the device, the directories appear under the device when plugged in, which is what I would expect to happen when the function above gets executed.

I have tried searching for a solution and cannot find the answer to my question.


回答1:


I made two methods. One for creating a file and one for appending to it. I think the issue is that you're not calling createNewFile.

private File CreateFile(String fileName)
{
    File file = new File(this.getFilesDir(), fileName);
    try
    {
        if(!file.exists())
        {
            file.createNewFile();
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return file;
}

private void appendToFile(String file, String content)
{
    try
    {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(file, this.MODE_APPEND));
        outputStreamWriter.append(content + "\n");
        outputStreamWriter.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}



回答2:


Alright after much searching and testing I finally came across a solution, linked via one of the other answers.

https://stackoverflow.com/a/28448843/979220

The solution was to scan the media files, which causes the files to propagate to the external storage, rather than staying in the emulated storage.



来源:https://stackoverflow.com/questions/37996241/android-asus-nexus-7-does-not-commit-emulated-memory-until-restart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!