android - 从内容提供者读取/写入文件

标签 android file android-contentprovider

我希望能够从 Content Provider 创建一个文件,但是我收到以下错误:

java.io.Filenotfoundexception: /0: open file failed: erofs (read-only file system)

我想做的是在应用程序从我的提供程序调用插入方法时创建一个文件。这是创建文件的代码摘录:

FileWriter fstream = new FileWriter(valueKey);
BufferedWriter out = new BufferedWriter(fstream); 
out.write(valueContent);
out.close();

最初我想使用 openFileOutput() 但该函数似乎未定义。

有人有办法解决这个问题吗?

编辑:我发现我还必须指定目录。下面是更完整的代码 fragment :

File file = new File("/data/data/Project.Package.Structure/files/"+valueKey);
file.createNewFile();
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
out.write(valueContent);
out.close();    

我也开启了权限

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

这次我得到一个错误说:

java.io.IOException: open failed: ENOENT (No such file or directory)

最佳答案

试试这个:

File parentDirectory = new File("/data/data/Project.Package.Structure/files");
if(!parentDirectory.exists())
{
    System.err.println("It seems like parent directory does not exist...");
    if(!parentDirectory.mkdirs())
    {
         System.err.println("And we cannot create it...");
         // we have to return, throw or something else
    }
}

File file = new File(parentDirectory, String.valueOf(valueKey));
file.createNewFile();

BufferedWriter out = new BufferedWriter(new FileWriter(file));
try
{
    out.write(valueContent);
    System.err.println("Now it works!");
}
catch(IOException e)
{
    e.printStackTrace();
}
// Anyway don't forget to close streams
finally
{
     out.close();   
}

关于android - 从内容提供者读取/写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9813665/

相关文章:

java - 查询 ContentProvider 时出现 "Invalid Tables"错误

Android跨应用数据传递

java - Azure 认知服务检测错误 : Unable to resolve host "centralus.api.cognitive.microsoft.com"

android - ParseObject 保存在本地。错误 : Unable to encode an unsaved parse file

python - 从用户那里获取输入,然后根据他们所说的命名一个 .txt 和一个 .csv 文件

file - 如何使用 GStreamer 标记或添加元数据到视频文件?

Android如何在Android中添加多个ContentProvider?

android - 恢复 ViewPager fragment 的演示者 (MVP)

java.lang.NoClassDefFoundError : Failed resolution of: Lcom/google/android/gms/common/GoogleApiAvailabilityLight;

java - 使用 jaybird 2.1.6 在 blob 字段中插入文件