kamal_tech_view
kamal_tech_view

Reputation: 4255

File creating and wirting content in .txt file

I am creating a file with getFilesDir() + file name what I am getting is filesfileName.txt, can you please tell me why I am getting this file name instead of fileName.txt.. thanks for your concern.


File file = new File(mContext.getFilesDir() + fileName+ ".txt");
            if (!file.exists()) {

                file.createNewFile();
                FileWriter f;
                try {

                    f = new FileWriter(mContext.getFilesDir() + fileName
                            + ".txt");
                    f.write(fbFriendList);
                    f.flush();
                    f.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

Upvotes: 1

Views: 221

Answers (4)

Moog
Moog

Reputation: 10193

You should use the overloaded constructor for file instead of using + to concatenate the file path this will add the path separator / for you. Also you can pass the File as an argument to the Filewriter constructor instead of repeating yourself with strings:

File file = new File(mContext.getFilesDir(), fileName+ ".txt");

FileWriter f;

try {
    f = new FileWriter(file);
    f.write(fbFriendList);
    f.flush();
    f.close();
} catch (IOException e1) {
    e1.printStackTrace();
}

For more information please refer to the official API documentation for File and FileWriter

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

You have to add "/".

File file = new File(mContext.getFilesDir() + "/" + fileName+ ".txt");

I'd suggest to use openFileOutput(String name, int mode) method - To create and write a private file to the internal storage.

Writer out
   = new BufferedWriter(
           new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_PRIVATE)));

Upvotes: 0

Nirali
Nirali

Reputation: 13805

Do this way

File file = new File(podcastFolder + File.separator + fileName + ".txt");

Upvotes: 0

Florian E.
Florian E.

Reputation: 11

Better use Path.Combine to create FullPath-Strings:

File file = new File(Path.Combine(mContext.getFilesDir(), fileName+ ".txt"));

Upvotes: 1

Related Questions