in my APP I receive a socket
periodically through String
. I need to save only the last received String but with the functions that I have obtained I am adding rows and Strings to the file. How can I overwrite the file every time I receive the coordinates to have only the last ones?
destroy the file and recreate it does not seem a very clean solution, is there any way to simply write on it?
I leave you the ones I have currently created:
Create file if it does not exist:
protected boolean crearSiNoExiste(String nombreFichero, String contenido){
file = new File(getFilesDir(), nombreFichero);
Log.d("log1", nombreFichero);
//Si el Fichero no existe se crea con una entrada inicial
if (!file.exists()) {
try{
FileOutputStream out = new FileOutputStream(file);
out.write(contenido.getBytes());
out.close();
Toast.makeText(this, "Creada categoría " + nombreFichero, Toast.LENGTH_SHORT).show();a
}catch (IOException e){
Toast.makeText(this, "Error creando categoría", Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
Which checks if the file exists and if it does not create it.
The following is to add a line to the file, it is the one that I want to modify so that it overwrites everything:
protected boolean Entrada(){
//Comprobar que no hay ningún EditText vacío
if (categoria.getText().toString().isEmpty()) {
Toast.makeText(this, "No hay nombre de categoría", Toast.LENGTH_SHORT).show();
return true;
}
try {
OutputStreamWriter fout = new OutputStreamWriter(
openFileOutput(nomFichero, Context.MODE_APPEND));
fout.write(System.getProperty("line.separator"));
fout.write(categoria.getText().toString()); //Escribir término en inglés
fout.close();
}
catch (Exception ex) {
Toast.makeText(this, "Error añadiendo categoría", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}