Writing a file to sdcard

53,593

Solution 1

The openFileOutput() method writes data to your application's private data area (not the SD card), so that's probably not what you want. You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.

Solution 2

//------------------------------WRITING DATA TO THE FILE ---------------------------------      

btnWriteSDFile.setOnClickListener(new OnClickListener() 
    {
    public void onClick(View v)
    {       

        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
            myOutWriter.append(txtData.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(v.getContext(),"Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
            txtData.setText("");
        } 
        catch (Exception e) 
        {
            Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }


    }); 

//---------------------------READING DATA FROM THE FILE PLACED IN SDCARD-------------------//       
        btnReadSDFile.setOnClickListener(new OnClickListener()
        {

        public void onClick(View v) 
        {

        try {

            File myFile = new File("/sdcard/mysdfile.txt");
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
            String aDataRow = "";
            String aBuffer = "";
            while ((aDataRow = myReader.readLine()) != null) 
            {
                aBuffer += aDataRow ;
            }
            txtData.setText(aBuffer);
            myReader.close();
            Toast.makeText(v.getContext(),"Done reading SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
        } 
        catch (Exception e)
        {
            Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
        }
        }
        }); 

ALONG WITH THIS ALSO WRITE THIS PERMISSION IN Android.Manifest

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

Solution 3

Here is a sample:

// Log used as debug
File log = new File(Environment.getExternalStorageDirectory(), "Log.txt");
try {
    out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
    out.write(new Date().toString());
    out.write(" : \n");
} catch (Exception e) {
    Log.e(TAG, "Error opening Log.", e);
}
Share:
53,593
Sumit M Asok
Author by

Sumit M Asok

Updated on July 18, 2022

Comments

  • Sumit M Asok
    Sumit M Asok almost 2 years

    I'm trying to write a file from an Http post reply to a file on the sdcard. Everything works fine until the byte array of data is retrieved.

    I've tried setting WRITE_EXTERNAL_STORAGE permission in the manifest and tried many different combinations of tutorials I found on the net.

    All I could find was using the openFileOutput("",MODE_WORLD_READABLE) method, of the activity but how my app writes file is by using a thread. Specifically, a thread is invoked from another thread when a file has to be written, so giving an activity object didn't work even though I tried it.

    The app has come a long way and I cannot change how the app is currently written.

    Please, someone help me?


    CODE:

    File file = new File(bgdmanip.savLocation);
    FileOutputStream filecon = null;
    filecon = new FileOutputStream(file);
    
    byte[] myByte;
    myByte = Base64Coder.decode(seReply);
    
    bos.write(myByte);
    filecon.write(myByte);
    myvals = x * 11024;
    

    bgdmanip.savLocation holds the whole files path. seReply is a string reply from HttpPost response. The second set of code is looped with reference to x. The file is created but remains 0 bytes.

  • Sumit M Asok
    Sumit M Asok about 14 years
    Thank Erich. I'm passing the full path as string like this "/sdcard/filename.ext" . also the file was created but the file size remains 0 bytes. also i'm not able to use the push/pull file controls of the DDMS in eclipse.
  • Erich Douglass
    Erich Douglass about 14 years
    You might need to post some of your file writing code to help diagnose the problem. Not everything, but at least the basics of what's going on. Also, are you seeing any messages in LogCat?
  • Sumit M Asok
    Sumit M Asok about 14 years
    Erich, I have updated the code. no messages are created about file ops in LogCat. I changed code lots of time that I got errors in some code but don't recollect which code gave me errors.
  • Sumit M Asok
    Sumit M Asok about 14 years
    Erich, also i cannot see the push pull buttons in eclipse DDMS. Is this something about why I'm not able to write to file ? I can see the sdcard and files in it but no control buttons mentioned above are visible.
  • Dr. aNdRO
    Dr. aNdRO almost 11 years
    thats what we call a programmer's view
  • AndroidOptimist
    AndroidOptimist over 10 years
    here instead of edittext i would like to pass two string values and store them in a file in sdcard. How can i achieve that?
  • Pir Fahim Shah
    Pir Fahim Shah over 10 years
    @Alliswell Please follow this link, hope you will get your solution stackoverflow.com/questions/9962896/…
  • Pir Fahim Shah
    Pir Fahim Shah over 10 years
    @Alliswell Its great that you got your solution, now owe me a lunch, hahahah. forward with luck