rosekarma
rosekarma

Reputation: 117

Android: problems creating a file

I'm writing an Android application in which I want to create text files in a particular folder and afterwards I want to read the files from my device. I'm doing this way:

 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());
        }

The problem is that in this way I create another folder instead of a text file. What can I do? Thanks

Upvotes: 1

Views: 74

Answers (2)

rosekarma
rosekarma

Reputation: 117

I found the solution and I want to share it with you:

 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());
    }

I hope this could help other people having the same problem. Good luck

Upvotes: 0

RajV
RajV

Reputation: 7200

Instead of:

f.mkdirs();

do:

path.mkdirs();

Upvotes: 2

Related Questions