尝试在外部存储中创建和写入文本文件时收到异常(Android Studio)

时间:2015-12-07 18:54:45

标签: android

这是我的写入方法的代码片段,当我想将数据写入此文件时,我可以调用该代码片段。

public void Write(String file,String data)     {

    File rootsd= Environment.getExternalStorageDirectory();
    File datafolder= new File(rootsd.getAbsolutePath()+"/Data");
    if(!datafolder.isDirectory())
    {
        try
        {
            datafolder.mkdir();
        }
        catch (Exception e)
        {
            Log.e("Error","Directory was not created");
        }
    }
    File datafile= new File(datafolder,file);
    try {
        if (!datafile.exists())
        {
            datafile.createNewFile();
        }
            writer = new BufferedWriter(new FileWriter(datafile));
            writer.write(data);
            writer.close();
    }
    catch (Exception e) {
        Log.e("Error", "File not found");
    }

}

由于某种原因,这会自动进入catch异常并返回File not Found,我不太清楚问题是什么,我似乎无法在线找到解决方案。感谢所有帮助,谢谢!

编辑:Logcat异常

Caused by: java.io.IOException: open failed: ENOENT (No such file or directory)
        at java.io.File.createNewFile(File.java:941)
        at uwpsych.ocdstopwatch.Q1.Write(Q1.java:157)
        at uwpsych.ocdstopwatch.Q1.SaveData(Q1.java:142)

at java.lang.reflect.Method.invoke(Native Method)

1 个答案:

答案 0 :(得分:0)

AndroidManifest.xml添加

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

如果你想阅读文件add和

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