Necesito una aplicación de muestra que demuestre guardar archivos de caché en Android y también cómo usar el método getCacheDir()?
¿Alguien me puede ayudar a resolver este problema? Necesito guardar el archivo en un directorio absoluto y necesito analizar ese archivo.
Gracias de antemano.Necesita un programa de ejemplo para "guardar archivos de caché" en Android
Respuesta
A menos que realmente necesita que sea caché, usted debe buscar en el almacenamiento de los archivos más persistente:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
No he intentado trabajar con la memoria caché, pero parece que una vez que la manejar, debería funcionar con los mismos comandos usados para los archivos persistentes.
Uso (en una actividad):
String textToCache = "Some text";
boolean success = GetCacheDirExample.writeAllCachedText(this, "myCacheFile.txt", textToCache);
String readText = GetCacheDirExample.readAllCachedText(this, "myCacheFile.txt");
GetCacheDirExample.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import android.content.Context;
public class GetCacheDirExample {
public static String readAllCachedText(Context context, String filename) {
File file = new File(context.getCacheDir(), filename);
return readAllText(file);
}
public static String readAllResourceText(Context context, int resourceId) {
InputStream inputStream = context.getResources().openRawResource(resourceId);
return readAllText(inputStream);
}
public static String readAllFileText(String file) {
try {
FileInputStream inputStream = new FileInputStream(file);
return readAllText(inputStream);
} catch(Exception ex) {
return null;
}
}
public static String readAllText(File file) {
try {
FileInputStream inputStream = new FileInputStream(file);
return readAllText(inputStream);
} catch(Exception ex) {
return null;
}
}
public static String readAllText(InputStream inputStream) {
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while ((line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
public static boolean writeAllCachedText(Context context, String filename, String text) {
File file = new File(context.getCacheDir(), filename);
return writeAllText(file, text);
}
public static boolean writeAllFileText(String filename, String text) {
try {
FileOutputStream outputStream = new FileOutputStream(filename);
return writeAllText(outputStream, text);
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
}
public static boolean writeAllText(File file, String text) {
try {
FileOutputStream outputStream = new FileOutputStream(file);
return writeAllText(outputStream, text);
} catch(Exception ex) {
ex.printStackTrace();
return false;
}
}
public static boolean writeAllText(OutputStream outputStream, String text) {
OutputStreamWriter outputWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputWriter);
boolean success = false;
try {
bufferedWriter.write(text);
success = true;
} catch(Exception ex) {
ex.printStackTrace();
} finally {
try {
bufferedWriter.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
return success;
}
}
Bueno, pero escribir siempre devuelve falso. Edite writeAllText para que sea verdadero o falso si fue una excepción. –
Cambié el código un poco para arreglarlo. Creo que debería hacerlo. – Nate
Esto debe colocarse en la Documentación si ya no está allí –
/** Getting Cache Directory */
File tempFile;
File cDir = getBaseContext().getCacheDir();
/* Makes a textfile in the absolute cache directory */
tempFile = new File(cDir.getPath() + "/" + "textFile.txt") ;
/* Writing into the created textfile */
FileWriter writer=null;
try {
writer = new FileWriter(tempFile);
writer.write("hello workd!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
/* Reading from the Created File */
String strLine="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tempFile);
BufferedReader bReader = new BufferedReader(fReader);
while((strLine=bReader.readLine()) != null ){
text.append(strLine+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
- 1. Necesita guardar un puntaje alto para un juego de Android
- 2. cómo guardar los archivos descargados en la caché de Android
- 3. ¿Cómo guardar/guardar en caché un objeto de clase personalizado en Android?
- 4. Necesita un ejemplo de sqlite con Monodroid
- 5. ¿Cómo guardar en caché las vistas en Android?
- 6. Necesita algún ejemplo de UILocalNotifications
- 7. Necesidad programa de ejemplo para lanzar InterruptedException
- 8. Guardar página web en caché usando webview en android
- 9. PHP APC ¿Guardar en caché o no?
- 10. Guardar archivos en cacao
- 11. Necesita un ejemplo de Hello World en IntelliJ IDEA
- 12. ¿Cómo almacenar archivos en el directorio de caché de Android?
- 13. ¿Guardar en caché un control de usuario en ASP.NET?
- 14. Cómo guardar en caché plantillas de bigote?
- 15. ¿El DNS de Android necesita calentamiento?
- 16. Eclipse: al guardar ejecutar un programa
- 17. Zend Framework: necesita un ejemplo típico de ACL
- 18. Necesita un buen ejemplo: Google Calendar API en Javascript
- 19. ¿Cómo guardar en caché los datos de la vista de lista en android?
- 20. ¿Hay una directiva simple Archivos de programa/Archivos de programa (x86) para C++ en Windows?
- 21. cómo guardar en caché un lambda en C++ 0x?
- 22. limpiando un caché de vistas web para archivos locales
- 23. Caché de archivos Python
- 24. Ejemplo de subprocesamiento en Android
- 25. ¿Cómo guardar archivos en un iPhone?
- 26. Ejemplo de DatePicker en android
- 27. Ejemplo de Android SSLEngine
- 28. Ejemplo de Android AudioRecord
- 29. ¿Necesita ayuda para editar archivos .lnk?
- 30. Ejemplo de Android JSoup
Hola, cualquier actualización con respecto a mi consulta. ¿Alguien puede ayudarme a resolver este problema? –