zee
zee

Reputation: 502

Write /Read String Array to File in Android, using internal or external storage whichever is available

I am downloading a json response array string from network and displaying a listview using this data.I want to store this response for first time in a file stored under internal/external storage, so i dont have to download the data again in future. How can i store this response in a internal/external storage file and read it later when my application starts afresh again.And File should be created first time only and later when application is started again, a check to whether file exists or not should be in place. Any examples /utility class where this has been done?

Here is my code... The Problem with this code is...it always creates a new directory and a new file.

public class FileCache {

    static File cacheDir;
    static final String DIRECTORY_ADDRESS = "/Android/data/com.example.savefiletostoragedemo/.newDirectory";
    static final String TAG="DEMO";
    public static void createDirectory(Context context){
        Log.i(TAG,"createDirectory() called...");

        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
             cacheDir = new File(Environment.getExternalStorageDirectory(),DIRECTORY_ADDRESS);
             Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.exists());
        }

        else{
            cacheDir=context.getCacheDir();
            Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.exists());
        }


        if(!cacheDir.exists()){
             cacheDir.mkdirs();
             Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
        }
        else{
            Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
        }

    }    

    public static File getFile(String filename){
        //String filename=String.valueOf(url.hashCode());
        File f = new File(cacheDir, filename);
        return f;
    }

    public static void saveFile(String dataToWrite, File file){
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
            outputStreamWriter.write(dataToWrite);
            outputStreamWriter.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }
    public static String readFromFile(File file){
        try{
            InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
             String receiveString = "";
             StringBuilder stringBuilder = new StringBuilder();

             while ( (receiveString = bufferedReader.readLine()) != null ) {
                 stringBuilder.append(receiveString);
             }
             bufferedReader.close();
             inputStreamReader.close();
             return stringBuilder.toString();
        }
        catch (FileNotFoundException e) {   
        } catch (IOException e) {
        }
        return null;

    }


public static void clear(){
    File[] files=cacheDir.listFiles();
    if(files==null)
        return;
    for(File f:files)
        f.delete();
}
}

I call createDirectory() in Application class

MainActivity.Java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownloadUrsl().execute(null,null,null);
    }



    private class DownloadUrsl extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... arg0) {
            File f = getJson("LISTVIEWDATA");
            //String jsonString =FileCache.readFromFile(f);
            //Log.i("DEMO", "DATA Read from file is:[ "+jsonString+" ]")
            return null;
        }
        private File getJson(String filename) {
            File f = FileCache.getFile(filename);
            if(f != null && f.isFile()) {
                String jsonString =FileCache.readFromFile(f);
                Log.i("DEMO", "DATA Read from file is:[ "+jsonString+" ]");
                return f;
            }

            try {
                Log.i("DEMO", "Starting data download...");
                HttpClient httpclient = new DefaultHttpClient();
                // make GET request to the given URL
                URI uri = new URI("");
                HttpResponse httpResponse = httpclient.execute(new HttpGet(uri));
                String response =EntityUtils.toString(httpResponse.getEntity());

                Log.i("DEMO", "DATA Received from net is:[ "+response+" ]");

                JSONArray array=new JSONArray(response);
                FileCache.saveFile(array.toString(), f);
                return f;                      
            } catch (Exception ex) {
                return null;
            }
        }
}

Issues with this Code: This code always creates a new directory when application starts...And also creates a new file everytime the data is requested.I also tried isDirectory(), didnt work.

Upvotes: 2

Views: 4380

Answers (2)

zee
zee

Reputation: 502

here is how i did it.. Thank you guys For Your Help..:)

public static void createDirectory(Context context){ Log.i(TAG,"createDirectory() called...");

    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
        File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
        cacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
        Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.isDirectory());
    }

    else{
        cacheDir=context.getCacheDir();
        Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.isDirectory());
    }


    if(!cacheDir.isDirectory()){
         cacheDir.mkdirs();
         Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
    }
    else{
        Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
    }

}    

public static File getFile(String filename){
    //String filename=String.valueOf(url.hashCode());
    File f = new File(cacheDir, String.valueOf(filename.hashCode()));
    return f;
}

public static void saveFile(String dataToWrite, File file){
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
        outputStreamWriter.write(dataToWrite);
        outputStreamWriter.close();
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}
public static String readFromFile(File file){
    try{
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
         BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
         String receiveString = "";
         StringBuilder stringBuilder = new StringBuilder();

         while ( (receiveString = bufferedReader.readLine()) != null ) {
             stringBuilder.append(receiveString);
         }
         bufferedReader.close();
         inputStreamReader.close();
         return stringBuilder.toString();
    }
    catch (FileNotFoundException e) {   
    } catch (IOException e) {
    }
    return null;

}

Upvotes: 1

Autocrab
Autocrab

Reputation: 3757

    private static final String cacheDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + MyUtilClass.class.getPackage().getName();

    public static void cacheResponse(String name, List<String> data) throws IOException {
        File f = new File(cacheDir + "/" + name);
        if (f.exists())
            return;
        Writer fw = new FileWriter(f);
        for (String line : data) {
            fw.write(line);
        }
        fw.close();
    }

Upvotes: 0

Related Questions