8

I need a Sample application that demonstrates saving cache files in Android and also how to use getCacheDir() method?
Can Anyone help me in sorting out this issue?I need to save file in an absolute directory and need to parse that file.
Thank in Advance.

1
  • Hi,Any updates regarding my query. Can any one help me in sorting out this issue? Oct 27, 2010 at 4:54

3 Answers 3

8

Use (in an Activity):

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;
    }

}
3
  • 2
    Nice, but write always return false. Edit writeAllText to get true or false if was exception. Oct 23, 2014 at 12:09
  • 1
    I changed the code a little to fix that. I think that should do it.
    – Nate
    Oct 23, 2014 at 13:31
  • 2
    This should be put in Documentation if it isn't there already Aug 10, 2016 at 15:45
3
  /** 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();
    }
0

Unless you really need it to be cache, you should look at storing the files more persistently:

http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

I haven't tried working with the cache, but it seems that once you get the handle, it should work with the same commands used for persistent files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.