【问题标题】:how to read and write file on android 4.4?如何在 android 4.4 上读写文件?
【发布时间】:2014-07-09 01:50:34
【问题描述】:

我需要打开画廊以显示特定目录中的图像,搜索后我按照这个 How to open gallery to show images in a specific directory

但 file.list 在 android 4.4 上返回一个 null String[] 比我写一些测试代码:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listDirectory("ExternalStorageRoot",
            Environment.getExternalStorageDirectory());
    listDirectory(
            "DCIM",
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
    writeFileTest();

}

private void writeFileTest() {
    String tag = "WriteTest";
    String path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).getAbsolutePath();
    path = path + "/testFile.txt";
    Log.d(tag, "path : " + path);

    File file=new File(path);

    FileOutputStream fileOutputStream;
    try {
        fileOutputStream = new FileOutputStream(file);      
        fileOutputStream.write("THIS IS A TEST LINE".getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }


}

private void listDirectory(String tag, File f) {
    Log.d(tag, "absolute path " + f.getAbsolutePath());
    Log.d(tag, "is dir " + f.isDirectory());
    Log.d(tag, "can read " + f.canRead());
    Log.d(tag, "can write " + f.canWrite());

    String[] fileNames = f.list();

    Log.d(tag, fileNames == null ? "fileNames is null"
            : "fileNames is not null");

    if (fileNames != null) {
        for (String string : fileNames) {
            Log.d(tag, "file -- " + string);
        }
    }
}

我还在 AndroidManifest.xml 中添加了这些行

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

编辑: 我搞砸了权限。现在一切正常!

【问题讨论】:

    标签: android


    【解决方案1】:

    4.4 更改了 sd 卡的文件权限。你不能再在你的个人目录之外写东西了。另见:http://www.androidcentral.com/kitkat-sdcard-changes

    【讨论】:

    • 我需要从特定文件夹读取图像文件并显示这些图片。但现在我无法读取(不修改它)
    • 对于 4.4 的这一更改有很多抱怨。他们确实处理得不好。但是您应该能够读取公共目录中的文件,据我了解,应该禁止其写入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多