How to save and retrieve InputStream in text file with less overhead - android

I am retrieving/downloading JSON feed as InputStreamReader and I need to pass this InputStreamReader to JsonReader for parsing it.
JsonReader reader = new JsonReader(isr); // isr is the InputStreamReader instance
Everything is okay. But I want to cache this InputStreamReader or this data in some other format into internal storage for later use. For caching, I am using text file to save. (AFAIK, android default cache saves data in external storage and some devices have no external storage).
For saving this file, I am using .txt file. But I am only able to save/cache String formatted data into file and read it as String. This is the code what I have written so far to write & read file:
public static void writeObject(Context context, String key, Object object)
throws IOException {
FileOutputStream fos = context
.openFileOutput(key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
fos.close();
}
public static Object readObject(Context context, String key)
throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(key);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
return object;
}
But this approach is taking too much conversion:
inputStreamReader -> inputStream -> String //to save
String -> inputStream -> inputStreamReader // retrieve
How can Save/cache this data with less overhead? Perhaps inputStreamReader needs to be converted to outputStreamReader or something like this to be writable. But I can't figure out the associative code to do this. What should be the code? Also can I cache this data by android's proposed way for later use intead of saving it as .txt file?

You can't short this process as String is best format to save information in file AFAIK. Also inputStreamReader & inputStream are not suitable object to be written. There may be other better explanatory answer :)

Related

Read textfile in Android - where to place the file

Where do I place a certain textfile in the project of Eclipse if I want to read the contents?
Which objects should I use?
I tried with the following syntax but the file could not be found? Maybe the computers filesystem is used in this case?
private void read() throws FileNotFoundException, IOException {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(fileReader);
String[] stringBuffer = new String[2];
String line;
int i = 0;
while ( (line = buffReader.readLine()) != null) {
stringBuffer[i] = line;
i++;
}
System.out.println(stringBuffer[0] + stringBuffer[1]);
}
My idea was that the search begins in the rootfolder of the project but I guess its completely wrong because the computers filesystem is used?
If you want to bundle this file with your Android application at build time, you have two choices: the /raw folder under /res or the /assets folder. You should place your file here and access it in the correct way for the chosen directory. For more information, read more about the built in folders for an Android project here.
For an example, if you store your text file in /assets/, which is most likely the correct place for a text file, you need to access the contents of the file using AssetManager. Let's assume you created a file called:
/assets/test.txt
You can access the file as such, assuming that you are doing this from an Activity, so that the this keyword points to your Activity:
AssetManager assetManager = this.getResources().getAssets();
InputStream input = assetManager.open("test.txt");
You can now use that input stream to read from the file in a way similar to how you have done in your original question. You can use that InputStream to create a BufferedReader, as below, assuming your text content is encoded in UTF-8:
BufferedReader br =
new BufferedReader(new InputStreamReader(input, "UTF-8"));

How to return location Object when loading file from internal file storage?

I am working on some way to store a GPS location within the internal file storage and retrieve it on demand in another method.
As I am new to Android I have tried out several ways and decided to go with the FileOutput-/InputStream as it is more comprehensible to me. I am working with the Android location API(http://developer.android.com/reference/android/location/Location.html).
I know that saving a location Object works technically via writing it to a string and later to bytes, but how can I load a saved file and have the saved location object returned?
My code approach:
public void saveCurrentLocation(){ //method works, I can see the saved file in the file explorer
Location currentLoc = gpsClass.getCurrentLocation(); //method within gpsClass that returns current location
try {
FileOutputStream fos = openFileOutput("SaveLoc", Context.MODE_PRIVATE);
fos.write(currentLoc.toString().getBytes());
fos.close();
}
catch(Exception e) { e.printStackTrace();}
}
public void loadSavedLocation() {
Location savedLoc;
try{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("SaveLoc")));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString);
}
gpsClass.update(??);
}
catch(Exception e) {e.printStackTrace();}
}
I'd like to pass the location Object readout in inputString to "gpsClass.update()" which only takes variables of the type Location. Do I have to make the Object serializable and if yes, how?
Many thanks in advance!
Why not persist your location objects into a SQLite database?
Or something like this:
Save:
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(your object);
os.close();
Load:
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
YourClass yourObject = (YourClass) is.readObject();
is.close();
return yourObject;
This should get you back on track

Saving a string serialized and buffered android JAVA.IO ObjectInputStream

I am saving out and loading mixed data types. I either have the saving part wrong or the loading part wrong. I am using buffered serial save and load method.
Variable lastFetchDate is defined as a string and initialized as "00/00/00".
It throws an error when reloading the data after it has been saved. What is wrong? I would have thought the opposite to writeBytes would be readBytes for a string.
Saving is as follows:
FileOutputStream fos = new FileOutputStream("userPrefs.dat");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeBytes(lastFetchDate);
// I close all streams
Loading is as follows:
FileInputStream fis = new FileInputStream("userPrefs.dat");
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
lastFetchDate=(String)ois.readObject(); //<<<<< Error thrown here
// I close all streams
You have written string as byte[] so need to read as byte[]
byte [] bString = new byte[lastFetchDate.length()*2];
ois.readFully(bString, 0, bString.length);
Or if you write as Object using writeObject method then you can read as object,
oos.writeObject(lastFetchDate);

Android: Write and Get Object

I want to write a serializable object to file in internal memory. Then, I want to load that object back from that file later. How could I do this in Android?
First of all your object must implement Serializable. Don't forget to add a serialVersionUID on the serializable class.
Then if you don't want to save specific field of the object mark it as transient.
Be sure all fields are serializable.
Next create a file in the internal memory and create an ObjectOutputStream to save your object. If you want to save in a specific folder you can create a path like this:
File path=new File(getFilesDir(),"myobjects");
path.mkdir();
Then you can use that path to save your object:
File filePath =new File(path, "filename");
FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
Reading is similar:
FileInputStream fis = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fis);
MyObjectClass myObject = (MyObjectClass ) in.readObject();
in.close();

how to read binary .AMF file in android

I am new to android and I want to read a binary file extension .AMF file.
I really need your help this is really urgent.
Thanks in advance.
I made a folder in RES named raw. Here is the code I tried, it says file not found.
FileInputStream in = new FileInputStream("R.raw.hello.txt");
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
in.close();
return inLine.toString();
From the Andoid SDK:
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
Read bytes from the file with read().
Then close the stream with close().
Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).
InputStream input = getResources().openRawResource(R.raw.hello.txt);

Categories

Resources