tags:

views:

41

answers:

2

Hi All,

I am new to android platform. I need to create a text file in android. Please let me know how to perform this task in android. I have written a code that is working fine in java but not in android. Please help me on this....the sample code that ihave written is :-

try { DataOutputStream dos = new DataOutputStream(new FileOutputStream("test.txt", true)); dos.writeBytes(dataLine); dos.close(); } catch (FileNotFoundException ex) {}

the above code snippet is working fine in java but not in android :(

Thanks, Ashish

+1  A: 

The Android Dev Guide explains it nicely:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

If you want the files you create to be visible to the outside world, use external storage. But as I said in the comment, make sure you're "being a good citizen". These files stick around even after the user uninstalls your app.

colithium
Hi, thanks for the reply...but the file is still not created using above snippet...also let me know the path where the file is getting created
Ashish
It gets created in your private dedicated "world". If you want it to be visible to the rest of the world then use external storage. But think long and hard about that. Are your files really important enough to keep around when the user uninstalls your app?
colithium
A: 

final File sdcard=Environment.getExternalStorageDirectory();

button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            File path=new File(sdcard,"textfile.txt");
            try {

                BufferedWriter wr=new BufferedWriter(new FileWriter(path));
                wr.write("Your Text Here");
                wr.close();

            } catch (IOException e) {

                e.printStackTrace();
            }

        }

Also you need to add a permission WRITE_EXTERNAL_STORAGE' to your manifest file

AceAbhi