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.
Related
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())
}
In my MainActivity class in onResume method I start writeFile method. The class which contains the method:
public class CacheFile {
private static final String TAG = "CacheFile";
private static final String mFileName="cachefile.txt";
private static File file;
//Write data into the file
public static void writeFile(Context context, String data) {
FileOutputStream outputStream=null;
String oldData=readFile(context)+"&"+data;
try {
file = new File(context.getCacheDir(), mFileName);
outputStream = new FileOutputStream(file);
if(data!=null) {
outputStream.write(oldData.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream!=null){
try{
outputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
//Read from file
public static String readFile(Context context) {
BufferedReader inputStream = null;
FileInputStream fis = null;
StringBuffer buffer = new StringBuffer();
String line;
try {
file = new File(context.getCacheDir(), mFileName);
fis=new FileInputStream(file);
inputStream = new BufferedReader(new InputStreamReader(fis));
while ((line = inputStream.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream!=null){
try{
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
if(fis!=null){
try{
fis.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return buffer.toString();
}
public static void deleteFile(Context context){
if(file!=null){
file.delete();
}
}
}
The first I readFile and add the information for writing but when I try to read file I get FileNotFoundException in line:
fis=new FileInputStream(file) (readfile method).
Why?
This means the file really doesn't exist. Do this:
file.createNewFile();
fis = new FileInputStream(file);
// Other code
You can read about createNewFile() here. It only creates the file if it doesn't already exist.
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
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.
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;
}
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();
}
I have HttpTransportSE object from KSOAP2 library.
I want to dump response file which may contains mote then simple 9697 character.
currently i am doing it by making transport.
transport.debug = true;
System.out.println("Response ----------"+transport.responseDump);
But it gives me half response with ... at last.
In its internal coding structure i found that it is using 256 bytes for creating and destroying it's responseDump like shown below:
package org.ksoap2.transport;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.List;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.xmlpull.v1.XmlPullParserException;
public class HttpTransportSE extends Transport
{
private ServiceConnection connection;
public HttpTransportSE(String url)
{
super(null, url);
}
public HttpTransportSE(Proxy proxy, String url)
{
super(proxy, url);
}
public HttpTransportSE(String url, int timeout)
{
super(url, timeout);
}
public HttpTransportSE(Proxy proxy, String url, int timeout) {
super(proxy, url, timeout);
}
public void call(String soapAction, SoapEnvelope envelope)
throws IOException, XmlPullParserException
{
call(soapAction, envelope, null);
}
public List call(String soapAction, SoapEnvelope envelope, List headers)
throws IOException, XmlPullParserException
{
if (soapAction == null) {
soapAction = "\"\"";
}
byte[] requestData = createRequestData(envelope);
this.requestDump = (this.debug ? new String(requestData) : null);
this.responseDump = null;
this.connection = getServiceConnection();
this.connection.setRequestProperty("User-Agent", "kSOAP/2.0");
if (envelope.version != 120) {
this.connection.setRequestProperty("SOAPAction", soapAction);
}
this.connection.setRequestProperty("Content-Type", "text/xml");
this.connection.setRequestProperty("Connection", "close");
this.connection.setRequestProperty("Content-Length", "" + requestData.length);
if (headers != null) {
for (int i = 0; i < headers.size(); i++) {
HeaderProperty hp = (HeaderProperty)headers.get(i);
this.connection.setRequestProperty(hp.getKey(), hp.getValue()); } }
this.connection.setRequestMethod("POST");
this.connection.connect();
OutputStream os = this.connection.openOutputStream();
os.write(requestData, 0, requestData.length);
os.flush();
os.close();
requestData = null;
List retHeaders = null;
InputStream is;
try { this.connection.connect();
is = this.connection.openInputStream();
retHeaders = this.connection.getResponseProperties();
} catch (IOException e) {
is = this.connection.getErrorStream();
if (is == null) {
this.connection.disconnect();
throw e;
}
}
if (this.debug) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[256];
while (true)
{
int rd = is.read(buf, 0, 256);
if (rd == -1)
break;
bos.write(buf, 0, rd);
}
bos.flush();
buf = bos.toByteArray();
this.responseDump = new String(buf);
is.close();
is = new ByteArrayInputStream(buf);
}
parseResponse(envelope, is);
return retHeaders;
}
public ServiceConnection getConnection() {
return (ServiceConnectionSE)this.connection;
}
protected ServiceConnection getServiceConnection() throws IOException {
return new ServiceConnectionSE(this.proxy, this.url, this.timeout);
}
public String getHost()
{
String retVal = null;
try
{
retVal = new URL(this.url).getHost();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
public int getPort()
{
int retVal = -1;
try
{
retVal = new URL(this.url).getPort();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
public String getPath()
{
String retVal = null;
try
{
retVal = new URL(this.url).getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
}
You found that its only
int rd = is.read(buf, 0, 256);
So, is there any options to increase responseDump size?
There is no limitation in ksoap, but it is in logcat. Logcat doesn't print long strings, so write in a file or write piece by piece in the log.
if (transport.debug)
{
byte[] is = transport.responseDump.getBytes();
String path="/mnt/sdcard/appData/";
File file = new File(path+"responseDump.xml");
if (!file.exists())
{
file.createNewFile();
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bos.write(is); bos.flush(); bos.close();
}