Android Deleting File From Storage OutputStream - android

I am trying to delete a file from storage however when I do it returns true as it's been deleted yet on next boot up reads out the file as if it still exists :/
package com.example.Mazer.Utilities;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import java.io.*;
public class ObjectSaver {
public static void writeObjectToFile(Context c, Object object, String filename) {
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = c.getApplicationContext().openFileOutput(filename, Activity.MODE_WORLD_READABLE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
Log.d("GameActivity", "Can't close objectOut ObjectOutputStream");
}
}
}
}
public static void deleteObjectFromFile(Context c, String filename) {
c.deleteFile( filename);
//NOPE
c.getApplicationContext().deleteFile(filename);
//NOPE
String s = c.getFilesDir().getAbsolutePath() + "/" + filename;
c.deleteFile(s);
//NOPE
}
public static Object readObjectFromFile(Context c, String filename) {
ObjectInputStream objectIn = null;
Object object = null;
try {
FileInputStream fileIn = c.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
// do nowt
}
}
}
return object;
}
}
As you can see I have added a few out of the million approaches I have tried, I have even tried over-writing the file.
I read from the file like so:
maze = (Maze) ObjectSaver.readObjectFromFile(Splash.this, "currentMaze");
and... I save to the file like so..
ObjectSaver.writeObjectToFile(context, new Maze(this), "currentMaze");

This might help:
import java.io.File;
public static void deleteObjectFromFile(Context c, String filename) {
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
}

boolean deleted = false;
File file = new File(selectedFilePath);
if (file.exists())
deleted = file.delete();
where selectedFilePath is the path of the file you want to delete - for example:
/sdcard/MyFolder/example.mp3

Related

Writing to a file, but file is empty when I read it in [duplicate]

I want to save a file to the internal storage by getting the text inputted from EditText. Then I want the same file to return the inputted text in String form and save it to another String which is to be used later.
Here's the code:
package com.omm.easybalancerecharge;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num = (EditText) findViewById(R.id.sNum);
Button ch = (Button) findViewById(R.id.rButton);
TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String opname = operator.getNetworkOperatorName();
TextView status = (TextView) findViewById(R.id.setStatus);
final EditText ID = (EditText) findViewById(R.id.IQID);
Button save = (Button) findViewById(R.id.sButton);
final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Get Text From EditText "ID" And Save It To Internal Memory
}
});
if (opname.contentEquals("zain SA")) {
status.setText("Your Network Is: " + opname);
} else {
status.setText("No Network");
}
ch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Read From The Saved File Here And Append It To String "myID"
String hash = Uri.encode("#");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:*141*" + /*Use The String With Data Retrieved Here*/ num.getText()
+ hash));
startActivity(intent);
}
});
}
I have included comments to help you further analyze my points as to where I want the operations to be done/variables to be used.
Hope this might be useful to you.
Write File:
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Read File:
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
For those looking for a general strategy for reading and writing a string to file:
First, get a file object
You'll need the storage path. For the internal storage, use:
File path = context.getFilesDir();
For the external storage (SD card), use:
File path = context.getExternalFilesDir(null);
Then create your file object:
File file = new File(path, "my-file-name.txt");
Write a string to the file
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write("text-to-write".getBytes());
} finally {
stream.close();
}
Or with Google Guava
String contents = Files.toString(file, StandardCharsets.UTF_8);
Read the file to a string
int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try {
in.read(bytes);
} finally {
in.close();
}
String contents = new String(bytes);
Or if you are using Google Guava
String contents = Files.toString(file,"UTF-8");
For completeness I'll mention
String contents = new Scanner(file).useDelimiter("\\A").next();
which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).
Notes
For each of these strategies, you'll be asked to catch an IOException.
The default character encoding on Android is UTF-8.
If you are using external storage, you'll need to add to your manifest either:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
or
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Write permission implies read permission, so you don't need both.
public static void writeStringAsFile(final String fileContents, String fileName) {
Context context = App.instance.getApplicationContext();
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
Logger.logError(TAG, e);
}
}
public static String readFileAsString(String fileName) {
Context context = App.instance.getApplicationContext();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
Logger.logError(TAG, e);
} catch (IOException e) {
Logger.logError(TAG, e);
}
return stringBuilder.toString();
}
Just a a bit modifications on reading string from a file method for more performance
private String readFromFile(Context context, String fileName) {
if (context == null) {
return null;
}
String ret = "";
try {
InputStream inputStream = context.openFileInput(fileName);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int size = inputStream.available();
char[] buffer = new char[size];
inputStreamReader.read(buffer);
inputStream.close();
ret = new String(buffer);
}
}catch (Exception e) {
e.printStackTrace();
}
return ret;
}
The Kotlin way by using builtin Extension function on File
Write: yourFile.writeText(textFromEditText)
Read: yourFile.readText()
check the below code.
Reading from a file in the filesystem.
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
// READ STRING OF UNKNOWN LENGTH
StringBuilder sb = new StringBuilder();
char[] inputBuffer = new char[2048];
int l;
// FILL BUFFER WITH DATA
while ((l = isr.read(inputBuffer)) != -1) {
sb.append(inputBuffer, 0, l);
}
// CONVERT BYTES TO STRING
String readString = sb.toString();
fis.close();
catch (Exception e) {
} finally {
if (fis != null) {
fis = null;
}
}
below code is to write the file in to internal filesystem.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(stringdatatobestoredinfile.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
I think this will help you.
I'm a bit of a beginner and struggled getting this to work today.
Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!
public class HighScore {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, "highscore.txt");
private int highScore = 0;
public int readHighScore() {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
highScore = Integer.parseInt(br.readLine());
br.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return highScore;
}
public void writeHighScore(int highestScore) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(highestScore));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Kotlin
class FileReadWriteService {
private var context:Context? = ContextHolder.instance.appContext
fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
val file = File(context?.filesDir, "files")
try {
if (!file.exists()) {
file.mkdir()
}
val fileToWrite = File(file, fileKey)
val writer = FileWriter(fileToWrite)
writer.append(sBody)
writer.flush()
writer.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
}
fun readFileOnInternalStorage(fileKey: String): String {
val file = File(context?.filesDir, "files")
var ret = ""
try {
if (!file.exists()) {
return ret
}
val fileToRead = File(file, fileKey)
val reader = FileReader(fileToRead)
ret = reader.readText()
reader.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
return ret
}
}
the first thing we need is the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
so in an asyncTask Kotlin class, we treat the creation of the file
import android.os.AsyncTask
import android.os.Environment
import android.util.Log
import java.io.*
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/MainFolder"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "cacheApp.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
if(result.isNotEmpty()){
//implement an interface or do something
Log.d("onPostExecuteSuccess", result)
}else{
Log.d("onPostExecuteFailure", result)
}
}
}
Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ReadandWrite {
private val mREAD = 9
private val mWRITE = 10
private var readAndWrite: Boolean = false
fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
if (Build.VERSION.SDK_INT < 23) {
readAndWrite = true
} else {
val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (mRead != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
} else {
readAndWrite = true
}
if (mWrite != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
} else {
readAndWrite = true
}
}
return readAndWrite
}
}
then in an activity, execute the call.
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this,this)
if(anRW){
pathToFileCreated = WriteFile().execute("onTaskComplete").get()
Log.d("pathToFileCreated",pathToFileCreated)
}
We can use this code to write String to a file
public static void writeTextToFile(final String filename, final String data) {
File file = new File(filename);
try {
FileOutputStream stream = new FileOutputStream(file);
stream.write(data.getBytes());
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then in the Main code, we use this, for example
writeTextToFile(getExternalFilesDir("/").getAbsolutePath() + "/output.txt", "my-example-text");
After that, check the file at Android/data/<package-name>/files.
The easiest way to append to a text file in kotlin:
val directory = File(context.filesDir, "LogsToSendToNextMunich").apply {
mkdirs()
}
val file = File(directory,"Logs.txt")
file.appendText("You new text")
If you want to just write to the file:
yourFile.writeText("You new text")
writing anything to the files, using bytes:
FileOutputStream(file).use {
it.write("Some text for example".encodeToByteArray())
}

android-how to save a view to sd card

i have a imageview , i am trying to save bitmap from imageview by this method
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
the rgb of saved image is not like that it looks in running app,so i am wondering if there is any way to save image view directly to a sd card rather getting the bitmap and then save it to sd card.
please help me i have tried everything.
You can read and write object using below code :
public static void witeObjectToFile(Context context, Object object, String filename)
{
ObjectOutputStream objectOut = null;
try
{
FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(object);
fileOut.getFD().sync();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (objectOut != null)
{
try
{
objectOut.close();
} catch (IOException e)
{
// do nowt
}
}
}
}
public static Object readObjectFromFile(Context context, String filename)
{
ObjectInputStream objectIn = null;
Object object = null;
try
{
FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
objectIn = new ObjectInputStream(fileIn);
object = objectIn.readObject();
} catch (FileNotFoundException e)
{
// Do nothing
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
} finally
{
if (objectIn != null)
{
try
{
objectIn.close();
} catch (IOException e)
{
// do nowt
}
}
}
return object;
}
For example ArrayList can be saved as :
ImageView abcImage = (ImageView) readObjectFromFile(context, AppConstants.FILE_PATH_TO_DATA);
and write as :
witeObjectToFile(context, abcImage, AppConstants.FILE_PATH_TO_DATA);
Try to use this
public void onClick(View v) {
if (v.getId() == R.id.btnSaveImage) {
imageView.setDrawingCacheEnabled(true);
Bitmap bm = imageView.getDrawingCache();
storeImage(bm);
}
}
private boolean storeImage(Bitmap imageData) {
// get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/yourappname/";
File sdIconStorageDir = new File(iconsStoragePath);
// create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
File file = new File(sdIconStorageDir.toString() + File.separator + "fileName");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
MediaScannerConnection.scanFile(this, new String[] { file.getPath() },
new String[] { "image/jpeg" }, null);
Toast.makeText(this, "Snapshot Saved to " + file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}

Can't write an Object. Read-only file system

I'm trying to save this Object, Inventory, to the internal storage. I have the saving and getting methods in the class itself. When I try and call the save method, I end up with the exception. I had the Exception message write to the Logcat, and here's what I got:
08-04 02:32:23.690: VERBOSE/alex(278): /test (Read-only file system)
The file /test is "Read-only file system", but I had allowed writing external storage in the Manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Here's the Inventory class. The last two methods are the save and read methods.
package com.androidbook.inventoryproject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import android.util.Log;
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
int numIngred;;
Ingredient[] ingredients;
ArrayList ingred = new ArrayList<Ingredient>();
public Inventory() {
numIngred = 0;
ingredients = new Ingredient[numIngred];
}
public int getNumIngred() {
return numIngred;
}
public String getIngredientName(int n) {
return ((Ingredient)ingred.get(n)).getName();
}
public Ingredient[] getIngredients() {
return ingredients;
}
public Ingredient getIngredient(int n) {
return (Ingredient)ingred.get(n);
}
public void addIngredient(String iname) {
numIngred++;
ingred.add(new Ingredient(iname));
}
public boolean saveInventory( Inventory inv) {
File suspend_f = new File("test");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(inv);
}
catch (Exception e) {
keep = false;
Log.v("alex", "" + e.getMessage());
}
finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
if (keep == false) suspend_f.delete();
}
catch (Exception e) { /* do nothing */ }
}
return keep;
}
public Inventory getInventory() {
File suspend_f = new File("test");
Inventory inven = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try{
fis = new FileInputStream(suspend_f);
ois = new ObjectInputStream(fis);
inven = (Inventory)ois.readObject();
}
catch (Exception e) {
String mess = e.getMessage();
}
finally {
try {
if (fis != null)
fis.close();
if (ois != null)
ois.close();
}
catch (Exception e) { }
}
return inven;
}
}
WRITE_EXTERNAL_STORAGE lets you write to the SD card, not to the filesystem root. You should try this:
File suspend_f = new File(Environment.getExternalStorageDirectory(), "test");
This verifies that the file you are using goes into a writable external folder.
EDIT: there is a bunch of other work you should do to verify that the SD card is available and writable. Read the specs to see how to make your file access robust by checking availability.

How to store images in Cache Memory

I am totally blank on this. I want to download the images from a Url and have to store it internally so that next time I need not connect to web and instead retrieve it from cache memory. But I am not sure how to do this. Can anyone help me with a code snippet.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
public class CacheStore {
private static CacheStore INSTANCE = null;
private HashMap<String, String> cacheMap;
private HashMap<String, Bitmap> bitmapMap;
private static final String cacheDir = "/Android/data/com.yourbusiness/cache/";
private static final String CACHE_FILENAME = ".cache";
#SuppressWarnings("unchecked")
private CacheStore() {
cacheMap = new HashMap<String, String>();
bitmapMap = new HashMap<String, Bitmap>();
File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(),cacheDir);
if(!fullCacheDir.exists()) {
Log.i("CACHE", "Directory doesn't exist");
cleanCacheStart();
return;
}
try {
ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(fullCacheDir.toString(), CACHE_FILENAME))));
cacheMap = (HashMap<String,String>)is.readObject();
is.close();
} catch (StreamCorruptedException e) {
Log.i("CACHE", "Corrupted stream");
cleanCacheStart();
} catch (FileNotFoundException e) {
Log.i("CACHE", "File not found");
cleanCacheStart();
} catch (IOException e) {
Log.i("CACHE", "Input/Output error");
cleanCacheStart();
} catch (ClassNotFoundException e) {
Log.i("CACHE", "Class not found");
cleanCacheStart();
}
}
private void cleanCacheStart() {
cacheMap = new HashMap<String, String>();
File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(),cacheDir);
fullCacheDir.mkdirs();
File noMedia = new File(fullCacheDir.toString(), ".nomedia");
try {
noMedia.createNewFile();
Log.i("CACHE", "Cache created");
} catch (IOException e) {
Log.i("CACHE", "Couldn't create .nomedia file");
e.printStackTrace();
}
}
private synchronized static void createInstance() {
if(INSTANCE == null) {
INSTANCE = new CacheStore();
}
}
public static CacheStore getInstance() {
if(INSTANCE == null) createInstance();
return INSTANCE;
}
public void saveCacheFile(String cacheUri, Bitmap image) {
File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(),cacheDir);
String fileLocalName = new SimpleDateFormat("ddMMyyhhmmssSSS").format(new java.util.Date())+".PNG";
File fileUri = new File(fullCacheDir.toString(), fileLocalName);
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(fileUri);
image.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
cacheMap.put(cacheUri, fileLocalName);
Log.i("CACHE", "Saved file "+cacheUri+" (which is now "+fileUri.toString()+") correctly");
bitmapMap.put(cacheUri, image);
ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(new File(fullCacheDir.toString(), CACHE_FILENAME))));
os.writeObject(cacheMap);
os.close();
} catch (FileNotFoundException e) {
Log.i("CACHE", "Error: File "+cacheUri+" was not found!");
e.printStackTrace();
} catch (IOException e) {
Log.i("CACHE", "Error: File could not be stuffed!");
e.printStackTrace();
}
}
public Bitmap getCacheFile(String cacheUri) {
if(bitmapMap.containsKey(cacheUri)) return (Bitmap)bitmapMap.get(cacheUri);
if(!cacheMap.containsKey(cacheUri)) return null;
String fileLocalName = cacheMap.get(cacheUri).toString();
File fullCacheDir = new File(Environment.getExternalStorageDirectory().toString(),cacheDir);
File fileUri = new File(fullCacheDir.toString(), fileLocalName);
if(!fileUri.exists()) return null;
Log.i("CACHE", "File "+cacheUri+" has been found in the Cache");
Bitmap bm = BitmapFactory.decodeFile(fileUri.toString());
bitmapMap.put(cacheUri, bm);
return bm;
}
}
Although the selected answer is correct, but it's a bit lengthy as its downloading image from the server first. Those who are just looking at how to save bitmap into cache for them we can use Android's native LruCache library. Here I have written a detailed article on the topic LruCache in Java & LruCache in Kotlin.
Java Class to save Bitmap in Cache:
import android.graphics.Bitmap;
import androidx.collection.LruCache;
public class MyCache {
private static MyCache instance;
private LruCache<Object, Object> lru;
private MyCache() {
lru = new LruCache<Object, Object>(1024);
}
public static MyCache getInstance() {
if (instance == null) {
instance = new MyCache();
}
return instance;
}
public LruCache<Object, Object> getLru() {
return lru;
}
public void saveBitmapToCahche(String key, Bitmap bitmap){
try {
MyCache.getInstance().getLru().put(key, bitmap);
}catch (Exception e){}
}
public Bitmap retrieveBitmapFromCache(String key){
try {
Bitmap bitmap = (Bitmap) MyCache.getInstance().getLru().get(key);
return bitmap;
}catch (Exception e){}
return null;
}
}

Need Sample Program on "saving Cache Files " in Android

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.
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;
}
}
/** 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();
}
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.

Categories

Resources