Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving to SD card as text file

   stopWriting = (Button) findViewById(R.id.save);
   stopWriting.setOnClickListener(new OnClickListener() {

       @SuppressLint("SdCardPath")
    public void onClick(View v) {
           // stop recording the sensor data
           try {

               myFile = new File("/sdcard/SensorData/" + txtData.getText() + ".txt");
               myFile.createNewFile();

               sData = new FileOutputStream(myFile);
               myOutWriter = new OutputStreamWriter(sData);
               myBufferedWriter = new BufferedWriter(myOutWriter);
               myPrintWriter = new PrintWriter(myBufferedWriter);

               //if(myFile != null )//stopFlag = mSensorManager.cancelTriggerSensor(null, null);
               Toast.makeText(getBaseContext(), "Done", Toast.LENGTH_SHORT).show();
           } catch (Exception e) {
               Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
           }
       }
   });

I am trying to save gyroscope data to txt file but it does not save. If anybody finds the problem, please help to me correct it.

like image 618
user2967906 Avatar asked Nov 08 '13 07:11

user2967906


2 Answers

Try this code:

public  void writeToFile(String fileName, String body)
    {
        FileOutputStream fos = null;

        try {
            final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/folderName/" );

            if (!dir.exists())
            {
                     if(!dir.mkdirs()){
                         Log.e("ALERT","could not create the directories");
                     }
            }

            final File myFile = new File(dir, fileName + ".txt");

            if (!myFile.exists()) 
            {    
                myFile.createNewFile();
            } 

            fos = new FileOutputStream(myFile);

            fos.write(body.getBytes());
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Also, remember to include the external storage permission in your manifest file:

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

and on android 6.0 to ask for permission for WRITE_EXTERNAL_STORAGE

like image 136
Gil Moshayof Avatar answered Nov 12 '22 03:11

Gil Moshayof


Have you used permission to write in sd?

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
like image 1
Gabi Moreno Avatar answered Nov 12 '22 01:11

Gabi Moreno