web-dev-qa-db-fra.com

Enregistrement sur une carte SD sous forme de fichier texte

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

J'essaie de sauvegarder les données du gyroscope dans un fichier txt mais cela ne sauve pas. Si quelqu'un trouve le problème, aidez-moi à le corriger.

12
user2967906

essayez ce code ça marche pour moi.

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(getBaseContext(),
                    "Done writing SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

n'oubliez pas de prendre la permission

<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
31
Jitesh Dalsaniya

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

Pensez également à inclure l’autorisation de stockage externe dans votre fichier manifeste:

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

et sur Android 6.0 pour demander l'autorisation pour WRITE_EXTERNAL_STORAGE

13
Gil Moshayof

Avez-vous utilisé la permission d'écrire en sd?

<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
1
Gabriel Moreno

Tout d'abord, déclarez cette autorisation à votre androidManifest.xml:

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

Puis écrivez ce code sur vos événements de clic sur un bouton

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

Essaye ça..

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();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(txtData.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD " + txtData.getText() + ".txt",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
}
   });

et également une autorisation de stockage externe dans votre fichier manifeste:

<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
0
Hariharan

Je le fais comme ça

public void write() 
{
    FileOutputStream output = null;

    try
    {
        String mediaState = Environment.getExternalStorageState();
        if(mediaState.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
        {
            output = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/download/shared.txt"));

            String str = "Hello, writing to a text file";
            byte[] b = encrypt2(str);
            output.write(b);
        }
        else 
        {
            // error
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            if (output != null)
                output.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

public static byte[] encrypt2(String value)
{
    byte[] input = value.getBytes();
    int nLen = input.length;

    if(nLen % 2 != 0)
    {
        nLen--;
    }

    byte temp;
    for (int i = 0; i < nLen; i += 2)
    {
        temp = input[i+1];
        input[i+1] = input[i];
        input[i] = temp;
    }
    // do encryption
    return Base64.encode(input, Base64.NO_WRAP);
}

Aussi cette permission est requise

<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
0
Rohit5k2