Manipulation fichier

1°) Sauvegarder un fichier qui est propre à l’application :

Avantage = accessible uniquement par l’application, supprimé lors de la désinstallation de l’application

2°) Créer un fichier « public » disponible por toutes les applications et persistant à la désinstallation :

exemple ici

Public files

Files that’ll remain on the storage even after the application is uninstalled by the user like media (photos, videos, etc.) or other downloaded files. There are 2 methods that we can use to get the public external storage directory for placing files:

  • getExternalStorageDirectory() – This returns the primary (top-level or root) external storage directory.
  • getExternalStoragePublicDirectorty() – This returns a top level public external storage directory for shoving files of a particular type based on the argument passed. So basically the external storage has directories like Music, Podcasts, Pictures, etc. whose paths can be determined and returned via this function by passing the appropriate environment constants.

3°) Exemple de fichier permettant de tester la durée d’utilisation d’une application (même si l’application et supprimée puis réinstallée) :

Source ici

 import android.app.Activity;  
 import android.app.AlertDialog;  
 import android.content.DialogInterface;  
 import android.os.Bundle;  
 import android.os.Environment;  
 import android.util.Log;  
 import android.widget.TextView;  
 import java.io.BufferedReader;  
 import java.io.DataInputStream;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 import java.text.SimpleDateFormat;  
 import java.util.Date;  
 import java.util.Locale;  
 import static android.os.Environment.getExternalStorageDirectory;  
 public class MainActivity extends Activity {  
   TextView response;  
   private String filename = "SampleFile.txt";  
   private String filepath;  
   File myExternalFile;  
   String myData = "";  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     response = (TextView) findViewById(R.id.response);  
     ////////  
     if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {  
       Log.d("FIC:ERREUR", "Impossible de créer le fichier");  
     } else {  
       File folder = new File(getExternalStorageDirectory() +  
           File.separator + "memtmp");  
       filepath = getExternalStorageDirectory() +  
           File.separator + "memtmp";  
       boolean success = true;  
       if (!folder.exists()) {  
         success = folder.mkdirs();  
         if (success) {  
           Log.d("FIC:1st crea fic", filepath +"/"+ filename);  
           try {  
             myExternalFile = new File(filepath, filename);  
             FileOutputStream fos = new FileOutputStream(myExternalFile);  
             String sDateJour;  
             Date date = new Date();  
             Locale current = MainActivity.this.getResources().getConfiguration().locale;  
             sDateJour = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, //ou .LONG  
                 current).format(date);  
             fos.write(sDateJour.getBytes());  
             fos.close();  
           } catch (IOException e) {  
             e.printStackTrace();  
           }  
         } else {  
           Log.d("FIC:ERREUR", "Impossible de créer " + filepath + filename);  
         }  
       }  
       //-- L'appli a déjà été lancée on teste si on est dans la période  
       else {  
         Log.d("FIC:Lecture date ", filepath +"/"+ filename);  
         myExternalFile = new File(filepath, filename);  
         try {  
           FileInputStream fis = new FileInputStream(myExternalFile);  
           DataInputStream in = new DataInputStream(fis);  
           BufferedReader br =  
               new BufferedReader(new InputStreamReader(in));  
           String strLine;  
           while ((strLine = br.readLine()) != null) {  
             myData = myData + strLine;  
           }  
           in.close();  
         } catch (IOException e) {  
           e.printStackTrace();  
         }  
         Log.d("FIC:Date=", myData);  
         comparedate(myData);  
       }  
     }  
   }  
   private static boolean isExternalStorageReadOnly() {  
     String extStorageState = Environment.getExternalStorageState();  
     if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
       return true;  
     }  
     return false;  
   }  
   private static boolean isExternalStorageAvailable() {  
     String extStorageState = Environment.getExternalStorageState();  
     if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
       return true;  
     }  
     return false;  
   }  
   /////////////////////////////////////////////////  
   //  
   //////////////////////////////////////////////////  
   private void comparedate(String CurrentDate) {  
     try {  
       SimpleDateFormat dates = new SimpleDateFormat("dd/MM/yyyy");  
       String FinalDate = dates.format(new Date());  
       Date date1;  
       Date date2;  
       //Setting dates  
       date1 = dates.parse(CurrentDate);  
       date2 = dates.parse(FinalDate);  
       //Comparing dates  
       long difference = Math.abs(date1.getTime() - date2.getTime());  
       long differenceDates = difference / (24 * 60 * 60 * 1000);  
       //Convert long to String  
       String dayDifference = Long.toString(differenceDates);  
       Log.d("FIC", "NbJours=" + dayDifference);  
       response.setText("Utilisation depuis "+dayDifference+" jours");  
       if (differenceDates>5)  
       {  
         AlertDialog.Builder alert = new AlertDialog.Builder(this);  
         alert.setTitle("Fin de période d'essai");  
         alert.setMessage("Arrêt de l'application");  
                   //-- Traitement bouton annueler  
           alert.setNegativeButton("Ok", new DialogInterface.OnClickListener() {  
             public void onClick(DialogInterface dialog, int whichButton) {  
               finish();  
             }  
           });  
           alert.show();  
         }  
     } catch (Exception exception) {  
       Log.d("FIC", "exception " + exception);  
     }  
   }  
 }  

Références :

http://blog.cindypotvin.com/saving-data-to-a-file-in-your-android-application/

http://stackoverflow.com/questions/17794974/create-folder-in-android

http://stackoverflow.com/questions/24751703/make-a-txt-file-in-internal-storage-in-android

http://www.journaldev.com/9400/android-external-storage-example-tutorial

https://www.tutorialspoint.com/android/android_internal_storage.htm

Articles récents
Commentaires récents
fatima dans Bienvenue !
AdminDroid dans Bienvenue !
fatima dans Bienvenue !
Archives
Catégories