Writing Resources from filesystem in Android - android

as I need to get a specific Frame from a Website I want to display in an WebView, I decided to grab the .html from the net and save it under file:///data/data//files/file.html. Stroed there I can edit it using regex or String methods.
Now two questions:
Is there a way to bind this file to an resource. e.g. to /res/raw/file.html and get it updated dynamically as i edit it? Or can i write the File directly to the resources?
Is this whole stuff I do there any good or performant at all? I mean maybe there is a better way to get the .html code between two tags from a Webpage and display it via WebView.
Kind regards
Markus

I believe that application assets are readonly. So you cannot write anything to it.
You can though, get access to the internal (device memory) files directory and write your data there. As for automatically updating the file, you'll have to take care of that in your code.
Here is an example of how you would go about writing a file (in my case a stream) to the files directory for your application
// ... code ...
// assumed variables:
// InputStream data, String directory, String filename
File storageLocation = new File(directory, filename)
try {
FileOutputStream outputStream = new FileOutputStream(storageLocation);
byte[] buff = new byte[0x2000];
int bytesRead = 0;
DataOutputStream dos = new DataOutputStream(outputStream);
while( (bytesRead = data.read(buffer)) > 0) { dos.write(buffer, 0, bytesRead); }
dos.flush();
dos.close();
outputStream.close();
} catch (Exception e) {
// TODO: Actually handle the exception
e.printStackTrace();
}
// ... more code ...

Related

How can I retrieve an Android resource from its name (in Kotlin)? [duplicate]

I want to open a file from the folder res/raw/.
I am absolutely sure that the file exists.
To open the file I have tried
File ddd = new File("res/raw/example.png");
The command
ddd.exists();
yields FALSE. So this method does not work.
Trying
MyContext.getAssets().open("example.png");
ends up in an exception with getMessage() "null".
Simply using
R.raw.example
is not possible because the filename is only known during runtime as a string.
Why is it so difficult to access a file in the folder /res/raw/ ?
With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName());
To get it as a InputStream
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
Here is example of taking XML file from raw folder:
InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML
Then you can:
String sxml = readTextFile(XmlFileInputStream);
when:
public String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).
BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.
Here are two approaches you can read raw resources using Kotlin.
You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.
Cheers mate 🎉
// R.raw.data_post
this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)

creating a copy of sdcard picture to another directory?

i am able to get the path of the picture i want to copy, and able to get the path from where i want it to be copy, but still cant find the way to copy them.
any suggestion?
private void copyPictureToFolder(String picturePath, String folderName)
throws IOException {
Log.d("debug", folderName);
Log.d("debug", picturePath);
try {
FileInputStream fileInputStream = new FileInputStream(picturePath);
FileOutputStream fileOutputStream = new FileOutputStream(folderName+"/");
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
fileInputStream.close();
fileOutputStream.close();
} catch (Exception e) {
Log.d("disaster","didnt work");
}
}
thanks.
You should use Commons-IO to copy a file, we are in 2013 ! No one wants do that manually. If you really want then you should consider a few things :
first a loop that copies your file, at every iteration you copy buffer.length bytes. In you current code, you don't loop and copy 512 bytes of source image into dest (whatever the source image size is).
take care of last iteration and only copy what you read
your try/catch structure is not correct, you should add a finally close to always close your source and destination file. Look here for an example : what is the exact order of execution for try, catch and finally?
With IOUtils, it will give something like
try {
IOUtils.copy( source, dest );
} finally {
IOUtils.closeQuietly( source );
IOUtils.closeQuietly( dest );
}
and don't catch anything, it will be forwarded to the caller.

How do I store data to the device?

I'm trying to figure how to store my application's data for the long term. Basically I get a list of data from from a web service, and I don't want to go back to the web service the next time the app runs. I'd prefer to just store it locally. How do I do this?
I don't mind serialising the data to any particular format. I don't see this on the Xamarin site for Android. There's a tutorial for iOS, but I'm not interested in that.
I personally copy the data from webservice in raw format in a text file on the memory.
So, I have just to open the inputStream from the file the same I did from the webservice and my code remains clean.
But I guess there are indeed thousands of ways to copy this data.
I just wanted to share the one I found more convenient.
The code just for information:
InputStream source = getStreamFromWebservice();// <= YOUR CODE HERE
File dir = context.getDir("CACHE", Context.MODE_PRIVATE);
dir.mkdirs();
File file = new File(dir, fileName);
// Write to Memory
try {
FileOutputStream f = new FileOutputStream(file);
byte[] buffer = new byte[32768];
int read;
try {
while ((read = source.read(buffer, 0, buffer.length)) > 0) {
f.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
}

Is there any way to acces file stored in project folder?

I have several files stored in my project /res/values folder, is there any way to open and read these files from my android application? Each file contains text informations about one level of my game.
I really appreciate any help.
I find what I needed here:
http://developer.android.com/guide/topics/data/data-storage.html
"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). "
Sorry if My question was not clear.
And big thanks to Radek Suski for some additional information and example. I appreciate that.
As far I know you can either access files within the directory "files" from your project directory or from the SD-Card.
But no other files
EDIT
FileInputStream in = null;
InputStreamReader reader = null;
try {
char[] inputBuffer = new char[256];
in = openFileInput("myfile.txt");
reader = new InputStreamReader(in);
reader.read(inputBuffer);
String myText = new String(inputBuffer);
} catch (Exception e) {;}
finally {
try {
if (reader != null)reader.close();
} catch (IOException e) {; }
try {
if (in != null)in.close();
} catch (IOException e) {;}
}
Then your file will be located in:
/data/data/yourpackage/files/myfile.txt

How to read file from phone's internal memory in android?

I have downloaded a file from HttpConnection using the FileOutputStream in android and now its being written in phone's internal memory on path as i found it in File Explorer
/data/data/com.example.packagename/files/123.ics
Now, I want to open & read the file content from phone's internal memory to UI. I tried to do it by using the FileInputStream, I have given just filename with extension to open it but I am not sure how to mention the file path for file in internal memory,as it forces the application to close.
Any suggestions?
This is what I am doing:
try
{
FileInputStream fileIn;
fileIn = openFileInput("123.ics");
InputStream in = null;
EditText Userid = (EditText) findViewById(R.id.user_id);
byte[] buffer = new byte[1024];
int len = 0;
while ( (len = in.read(buffer)) > 0 )
{
Userid.setText(fileIn.read(buffer, 0, len));
}
fileIn.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
String filePath = context.getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, fileName);
Similar post here
read file from phone memory
If the file is where you say it is, and your application is com.example.packagename, then calling openFileInput("123.ics"); will return you a FileInputStream on the file in question.
Or, call getFilesDir() to get a File object pointing to /data/data/com.example.packagename/files, and work from there.
I am using this code to open file in internal storage. i think i could help.
File str = new File("/data/data/com.xlabz.FlagTest/files/","hello_file.xml");

Categories

Resources