Android:创建文件时遇到问题

时间:2014-08-21 14:58:09

标签: android file

我正在编写一个Android应用程序,我想在特定文件夹中创建文本文件,之后我想从我的设备中读取文件。 我是这样做的:

 File sd = Environment.getExternalStorageDirectory();
    File f;
    FileWriter fw = null;

    String path = sd.getAbsolutePath() + "/Samples/";

    f = new File(path+File.separator+"filename.txt");
    if (!f.exists())
    {
        f.mkdirs();//Creates the directory named by this file, creating missing parent directories if necessary
        try
        {
            f.createNewFile();
            //fw = new FileWriter(f, true);
        }
        catch (IOException e)
        {
            Log.e("ERROR","Exception while creating file:"+e.toString());
        }

问题是,通过这种方式,我创建了另一个文件夹而不是文本文件。我能做什么?感谢

2 个答案:

答案 0 :(得分:2)

而不是:

f.mkdirs();

做的:

path.mkdirs();

答案 1 :(得分:0)

我找到了解决方案,我想与您分享:

 File sd = Environment.getExternalStorageDirectory();
    File folder;


    String path = sd.getAbsolutePath() ;


    folder = new File(path, dirName);

        if (!folder.exists()){
            folder.mkdirs();}
    try{
        File file = new File(folder, fileName+".txt");
        file.createNewFile();
    } catch (IOException e) {
        Log.e("ERROR", "Exception while creating file:" + e.toString());
    }

我希望这可以帮助其他人遇到同样的问题。祝你好运