• 26juin

    Ecrire et lire dans un fichier avec android



    Dans ce tuto je vais développer des méthodes me permettant de lire et écrire dans un fichier android. Pour faire cela je vais utiliser les class FileOutputStream, OutputStreamWriter pour l’écriture et les classes FileInputStream , InputStreamReader pour la lecture. J’utilise également la class Toast pour afficher des popups surgissant

    D’abord ma méthode me permettant d’écrire dans un fichier

    ?Download download.txt
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
      public void WriteSettings(Context context, String data){ 
            FileOutputStream fOut = null; 
            OutputStreamWriter osw = null; 
     
            try{ 
               fOut = context.openFileOutput("settings.dat",MODE_APPEND);       
                osw = new OutputStreamWriter(fOut); 
                osw.write(data); 
                osw.flush(); 
               //popup surgissant pour le résultat
                Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show(); 
                } 
                catch (Exception e) {       
                        Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show(); 
                } 
                finally { 
                   try { 
                          osw.close(); 
                          fOut.close(); 
                          } catch (IOException e) { 
                                   Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show(); 
                          } 
                } 
           }

    Ma méthode me permettant de lire dans mon fichier et de renvoyer le contenu sous forme de String (chaine de caractères) .

    ?Download download.txt
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    
    public String ReadSettings(Context context){ 
            FileInputStream fIn = null; 
            InputStreamReader isr = null; 
     
            char[] inputBuffer = new char[255]; 
            String data = null; 
     
            try{ 
             fIn = context.openFileInput("settings.dat");       
                isr = new InputStreamReader(fIn); 
                isr.read(inputBuffer); 
                data = new String(inputBuffer); 
               //affiche le contenu de mon fichier dans un popup surgissant
                Toast.makeText(context, " "+data,Toast.LENGTH_SHORT).show(); 
                } 
                catch (Exception e) {       
                          Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show(); 
                } 
                /*finally { 
                   try { 
                          isr.close(); 
                          fIn.close(); 
                          } catch (IOException e) { 
                            Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show(); 
                          } 
                } */
                return data; 
           }

    Pour tester ces deux méthodes je vais créer une fenêtre avec un bouton écrire, un bouton lire et une zone de saisie.
    le fichier xml de ma fenêtre test.xml

    ?Download download.txt
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    
    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="fill_parent" 
                  android:layout_height="fill_parent" 
                  android:orientation="vertical" >
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
     
    	<Button android:id="@+id/btecrire"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Ecrire" />
       <Button android:id="@+id/btvoir"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="voir" />
        <EditText  
    	android:id="@+id/text"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Ingredient"
        android:background="#D4D0C8"
        android:textColor="#000000"
        />
     
        <TextView android:id="@+id/text"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:text=""  />
     
    </LinearLayout> 
    </ScrollView>

    Je rajoute le code suivant, me permettant d’afficher ma fenêtre de test.xml et tester mes méthodes sur le click de mes différents boutons

    ?Download download.txt
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    setContentView(R.layout.test);
     Button btvoir = (Button) findViewById(R.id.btvoir);
     Button btecrire = (Button) findViewById(R.id.btecrire);
     btvoir.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
     
                  ReadSettings(lecontext);
         } 
         });  
     
    btecrire.setOnClickListener(new Button.OnClickListener() {
             public void onClick(View v) {
              TextView datatext = (TextView) findViewById(R.id.text);
             String sQuantite = datatext.getText()+"\n";
             WriteSettings(lecontext,sQuantite);
       } 
      });

    Résultat
    lireecrire1 lireecrire2

    Il est temps de mettre à profit les tutoriels d’Android France:
    Passez à la vitesse supérieure et investissez quelques dizaines d’euros pour acquérir les connaissances qui vous feront gagner de l’argent avec vos applications rendez-vous sur notre boutique Android-france pour ces formations en vidéo


    Formation Android en vidéo

    Partager cet article :

    Guy

    Co-fondateur du site Android france, senior lead developper, passionné de bière et de cigare cubain

    Twitter Google+ 

  • tupakito

    Bonsoir,

    Pour ceux qui n’aurais toujours pas réussi à compiler le code, voici ce que j’ai fait (si il y a des améliorations à faire, informez moi en ;) )

    package com.test.projet;

    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.io.FileOutputStream;
    import java.io.OutputStreamWriter;
    import java.io.InputStreamReader;
    import java.io.FileInputStream;
    import android.content.Context;
    import java.io.IOException;
    import android.widget.Button;
    import android.view.View;

    public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);

    Button btvoir = (Button) findViewById(R.id.btvoir);
    Button btecrire = (Button) findViewById(R.id.btecrire);

    btvoir.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
    Context lecontext = getBaseContext();
    ReadSettings(lecontext);
    }
    });

    btecrire.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
    TextView datatext = (TextView) findViewById(R.id.text);
    String sQuantite = datatext.getText()+ »\n »;
    Context lecontext = getBaseContext();
    WriteSettings(lecontext,sQuantite);
    }
    });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
    }

    public void WriteSettings(Context context, String data){
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    try{
    fOut = context.openFileOutput(« settings.dat »,MODE_APPEND);
    osw = new OutputStreamWriter(fOut);
    osw.write(data);
    osw.flush();
    //popup surgissant pour le résultat
    Toast.makeText(context, « Settings saved »,Toast.LENGTH_SHORT).show();
    }
    catch (Exception e) {
    Toast.makeText(context, « Settings not saved »,Toast.LENGTH_SHORT).show();
    }
    finally {
    try {
    osw.close();
    fOut.close();
    } catch (IOException e) {
    Toast.makeText(context, « Settings not saved »,Toast.LENGTH_SHORT).show();
    }
    }
    }

    public String ReadSettings(Context context){
    FileInputStream fIn = null;
    InputStreamReader isr = null;

    char[] inputBuffer = new char[255];
    String data = null;

    try{
    fIn = context.openFileInput(« settings.dat »);
    isr = new InputStreamReader(fIn);
    isr.read(inputBuffer);
    data = new String(inputBuffer);
    //affiche le contenu de mon fichier dans un popup surgissant
    Toast.makeText(context,  » « +data,Toast.LENGTH_SHORT).show();
    }
    catch (Exception e) {
    Toast.makeText(context, « Settings not read »,Toast.LENGTH_SHORT).show();
    }
    /*finally {
    try {
    isr.close();
    fIn.close();
    } catch (IOException e) {
    Toast.makeText(context, « Settings not read »,Toast.LENGTH_SHORT).show();
    }
    } */
    return data;
    }

    }

    Cordialement :)