Writing and Reading ArrayList<File> into android cache memory - android

I have a arrays of apk files, what I need is to do write the apk files of ArrayList into cache storage and read it back again as same ArrayList. I know how to insert a single file and retrieve back again from the cache. But whereas ArrayList objects as concern I completely stuck up with the solutions and methodology. Please help me. I am using following code for read and write into cache memory. Any modification or slight changes in my code will be more helpful to me. Thanks in advance
Actual code for Read and write single File
//Write to cache dir
FileWriter writer = null;
try {
writer = new FileWriter(tmpFile);
writer.write(text.toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
//Read to cache directory
String TMP_FILE_NAME = "base.apk";
File tmpFile;
File cacheDir = getBaseContext().getCacheDir();
tmpFile = new File(cacheDir.getPath() + "/" + TMP_FILE_NAME) ;
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tmpFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
Modified code for my requirement to insert ArrayList<File>
String tempFile = null;
public void writeFile(ArrayList<File> files(){
for(File file: files) {
FileWriter writer = null;
try {
writer = new FileWriter(file);
tempFile = file.getName().toString();
writer.write(file.getName().toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is where I stuck completely to read as ArrayList
What i tried is
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tempFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}

I found my own answer for my question after a longstruggle from the blog.
To Write a ArrayList<File>:
public static void createCachedFile (Context context, String key, ArrayList<File> fileName) throws IOException {
String tempFile = null;
for (File file : fileName) {
FileOutputStream fos = context.openFileOutput (key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject (fileName);
oos.close ();
fos.close ();
}
}
To Read a ArrayList<File>
public static Object readCachedFile (Context context, String key) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput (key);
ObjectInputStream ois = new ObjectInputStream (fis);
Object object = ois.readObject ();
return object;
}
Final code in my Activity
createCachedFile (MainActivity.this,"apk",adapter.getAppList ());
ArrayList<File> apkCacheList = (ArrayList<File>)readCachedFile (MainActivity.this, "apk");

Related

How to read a text file from a Class method

I want to use a Class method to read a text file & pass a return value.
My error is the line:
fis = openFileInput(FILE_NAME);
The error message is:
Cannot resolve method 'openFileInput(java.lang.String)'
I suspect it's because I'm not passing a context, or that Android does not know the full file path using my Class method code.
I want to use the Class method so I can call it from various Activities.
import java.io.FileInputStream;
public static String GetUserId(){
String str_return = null;
String FILE_NAME = "userid.txt";
try {
FileInputStream fis = null;
fis = openFileInput(FILE_NAME); \\<-- error is here
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try this :
File yourFile = new File("YOUR_TEXTFILE_PATH");
String data = null;
try (FileInputStream stream = new FileInputStream(yourFile)) {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
data = Charset.defaultCharset().decode(bb).toString(); //this is the data from your textfile
} catch (Exception e) {
e.printStackTrace();
}
And generating the textfile
File root = new File("YOUR_FOLDER_PATH");
//File root = new File(Environment.getExternalStorageDirectory(), folderName); //im using this
//creation of folder (if you want)
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, textFileName);
FileWriter writer;
writer = new FileWriter(gpxfile);
writer.append(textFileData);
writer.flush();
writer.close();
}
I have done it in one of my kotlin project likethis, It might work in Java too.
val textFromFile = openFileInput(filePath).reader().readText()

openFileInput always returning null

I'm writing a string to a file using the method saveData();
public void saveData(){
String fileName = "lifeClockSavedData";
String birthYear = "1986";
try {
FileOutputStream fileOutputStream = openFileOutput(fileName, MODE_PRIVATE);
fileOutputStream.write(birthYear.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And opening it in a widget activity using retrieve();
String messageString;
public void retrieve(Context context){
String fileName = "lifeClockSavedData";
try {
String message;
FileInputStream fileInputStream = context.getApplicationContext().openFileInput(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((message = bufferedReader.readLine())!=null);{stringBuffer.append(message);}
messageString = stringBuffer.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
As far as I can tell, this should set messageString to "1986", but the value is always "null".
I'd appreciate a pointer as to what's going wrong.
edit: This question isn't a duplicate of context.openFileInput() returning null when trying to access a stored file
as I'm not trying to get openFileInput() to accept a path
I'm writing a string to a file
No, you are not. You are writing bytes to file.
Either:
Write a string to the file (e.g., via a PrintWriter wrapped around an OutputStreamWriter), or
Read bytes from the file, then construct a String from those bytes
scrapped:
while ((message = bufferedReader.readLine())!=null);{stringBuffer.append(message);}
replaced with:
stringBuffer.append(bufferedReader.readLine());
Not sure why it worked, as bufferedReader.readline() wasn't null.

Android not creating/appending a.txt file

This is what doing to read from a .txt file in my android activity. Though the app runs, I find that no file is created/appended. In logcat following line is shown,
java.io.FileNotFoundException: /home/Desktop/RiaC_android/Test/app/src/main/assets/SampleFile.txt: open failed: ENOENT (No such file or directory)
The code I'm currently using, though I have tried before,
BufferedWriter out = new BufferedWriter(
new FileWriter("test_File.txt"));
however, the result remains same.
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView);
File testFile = new File("/home/Desktop/RiaC_android/Test/app/src/main/assets", "SampleFile.txt");
FileWriter writer = null;
try {
writer = new FileWriter(testFile, true);
writer.write("Hello File!!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
if (testFile.exists())
tv.setText("File created!!");
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Any suggestions about what I'm doing wrong?
You can't write file to assets folder.The assets folder is read-only at runtime. Pick a different location to save your data. ie , Environment.getExternalStorageDirectory() don't use Environment.getExternalStorageDirectory().getAbsolutePath().
For reading files from asset use the following method
public String readFromAsset(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
You can't write to /asset directory because it is read-only.
The assets folder is like folders res, src, gen, etc. These are all useful to provide different files as input to build system to generate APK file for your app.
All these are read-only while your app is running. At run-time you can write to SD card.
You do not access assets/ at runtime using File. You access assets/ at runtime using AssetManager, which you can get via getResources().getAssets().
To read from /asset folder, use the following code:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("SampleFile.txt");
if ( inputStream != null)
Log.d("TAG", "It worked!");
} catch (Exception e) {
e.printStackTrace();
}
You cannot modify files in asset folder. just think them readonly files.
If you want to create text file and modify them, create a file using getExternalCacheDir and new File method.
public static File CreateTextFile(Context context, String filename) throws IOException {
final File root = context.getExternalCacheDir();
return new File(root, filename);
}
EDIT APPENDED BELOW
1. To write text simply, do as below
String text = "bla bla";
FileWriter writer=null;
try {
File file = CreateTextFile("something.txt"); // proposed method
if(!file.exists())
file.createNewFile();
writer = new FileWriter(file);
/** Saving the contents to the file*/
writer.write(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2. To read cache file,
Check this link: https://stackoverflow.com/a/5971667/361100
3. One more example
Below example is to write fetched text from internet.
String webUrl = "http://www.yourdata.com/data.txt";
try {
URL url = new URL(webUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
File file = CreateTextFile("something.txt"); // proposed method
if(!file.exists())
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize)
filepath=file.getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
filepath=null;
}

How to return file object from assets in Android?

I want to return file object from assests folder. In Similar questions's response, it's returned InputStream class object, but I don't want to read content.
What I try to explain, there is an example.eg file in assests folder. I need to state this file as File file = new File(path).
Try this:
try {
BufferedReader r = new BufferedReader(new InputStreamReader(getAssets().open("example.csv")));
StringBuilder content = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
content(line);
}
} catch (IOException e) {
e.printStackTrace();
}
As far as I know, assets are not regular accessible files like others.
I used to copy them to internal storage and then use them.
Here is the basic idea of it:
final AssetManager assetManager = getAssets();
try {
for (final String asset : assetManager.list("")) {
final InputStream inputStream = assetManager.open(asset);
// ...
}
}
catch (IOException e) {
e.printStackTrace();
}
You can straight way create a file using InputStream.
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}

Using InputStream to read file from internal storage

I've searched for a couple days, and all I find is using bufferedReader to read from a file on internal storage. Is it not possible to use InputStream to read from a file on internal storage?
private void dailyInput()
{
InputStream in;
in = this.getAsset().open("file.txt");
Scanner input = new Scanner(new InputStreamReader(in));
in.close();
}
I use this now with input.next() to search my file for the data that I need. It all works fine, but I would like to save new files to internal storage and read from them without changing everything to bufferedReader. Is this possible or do I need to bite the bullet and change everything? FYI I don't need to write, only read.
To write a file.
String FILENAME = "file.txt";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
to read
void OpenFileDialog(String file) {
//Read file in Internal Storage
FileInputStream fis;
String content = "";
try {
fis = openFileInput(file);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {
}
content += new String(input);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
content will Contain your File Data.
You may try following code when you face a condition to read a file from a subfolder in internal storage. Sometimes you may get problems with openFileInput whey you trying to passing context.
here is the function.
public String getDataFromFile(File file){
StringBuilder data= new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String singleLine;
while ((singleLine= br.readLine()) != null) {
data.append(singleLine);
data.append('\n');
}
br.close();
return data.toString();
}
catch (IOException e) {
return ""+e;
}
}

Categories

Resources