Le code ci-dessous crée un répertoire Documents , puis un sous-répertoire pour l'application et y enregistre les fichiers.
public class loadDataTooDisk extends AsyncTask<String, Integer, String> {
String sdCardFileTxt;
@Override
protected String doInBackground(String... params)
{
//check to see if external storage is avalibel
checkState();
if(canW == canR == true)
{
//get the path to sdcard
File pathToExternalStorage = Environment.getExternalStorageDirectory();
//to this path add a new directory path and create new App dir (InstroList) in /documents Dir
File appDirectory = new File(pathToExternalStorage.getAbsolutePath() + "/documents/InstroList");
// have the object build the directory structure, if needed.
appDirectory.mkdirs();
//test to see if it is a Text file
if ( myNewFileName.endsWith(".txt") )
{
//Create a File for the output file data
File saveFilePath = new File (appDirectory, myNewFileName);
//Adds the textbox data to the file
try{
String newline = "\r\n";
FileOutputStream fos = new FileOutputStream (saveFilePath);
OutputStreamWriter OutDataWriter = new OutputStreamWriter(fos);
OutDataWriter.write(equipNo.getText() + newline);
// OutDataWriter.append(equipNo.getText() + newline);
OutDataWriter.append(equip_Type.getText() + newline);
OutDataWriter.append(equip_Make.getText()+ newline);
OutDataWriter.append(equipModel_No.getText()+ newline);
OutDataWriter.append(equip_Password.getText()+ newline);
OutDataWriter.append(equipWeb_Site.getText()+ newline);
//OutDataWriter.append(equipNotes.getText());
OutDataWriter.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return null;
}
}
Celui-ci construit le nom du fichier
private String BuildNewFileName()
{ // creates a new filr name
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
StringBuilder sb = new StringBuilder();
sb.append(today.year + ""); // Year)
sb.append("_");
sb.append(today.monthDay + ""); // Day of the month (1-31)
sb.append("_");
sb.append(today.month + ""); // Month (0-11))
sb.append("_");
sb.append(today.format("%k:%M:%S")); // Current time
sb.append(".txt"); //Completed file name
myNewFileName = sb.toString();
//Replace (:) with (_)
myNewFileName = myNewFileName.replaceAll(":", "_");
return myNewFileName;
}
J'espère que cela t'aides! Il m'a fallu beaucoup de temps pour le faire fonctionner.