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

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

Related

FileReader file path in Android

I created A Buffered Reader, File Reader in my Android app and placed two text files inside raw folder. Now I have to pass a file path into File Reader, but what is the path of my file now?
BufferedReader reader = new BufferedReader(new FileReader("path"));
image link
but what is the path of my file now?
You don't have to pass file path into FileReader for reading file, here you can check following code snippet.
InputStream inputStream = null;
try {
inputStream = getResources().openRawResource(R.raw.hello_world);
byte[] reader = new byte[inputStream.available()];
while (inputStream.read(reader) != -1) {}
editField.setText(new String(reader));
editField.setSelection(editField.getText().length());
} catch(IOException e) {
Log.e(LOG_APP_TAG, e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e(LOG_APP_TAG, e.getMessage());
}
}
}
}
Raw folder is for what in ANDROID
Arbitrary files to save in their raw form. To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename.In above example R.raw.hello_world.
However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). Files in assets/ are not given a resource ID, so you can read them only using AssetManager.
Raw mostly used with media files.
By default, you will be working in your present class path. So, you have to go back to the folder where the raw files is present and go inside it and access the files you want to.
file:///
will go back to your project directory, the one that contains all the folders. From there , you can access the raw folder.

Why does AssetManager list() not show my assets folder?

In my Android app I have packaged a file in the /assets folder that needs to be copied to the SDCARD. When I list the contents of the assets folder to a String[] I get "images", "sounds", "webkit" and "kioskmode" but not my file manually added to the assets folder.
My code is here:
private void copyAsset () {
AssetManager am = getApplicationContext().getAssets();
String[] files = null;
try {
files = am.list("");
} catch (IOException e) {
}
for (String filename : files) {
if (filename.equals("images") || filename.equals("kioskmode") ||
filename.equals("sounds") || filename.equals("webkit")) {
Log.i(TAG, "Skipping folder " + filename);
continue;
}
InputStream in = null;
OutputStream out = null;
try {
in = am.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory().getPath(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Error copying asset ", e);
}
}
}
Does it make a difference that this is a second class in my app and is called in my MainActivity using Intent showHelper = new Intent(this, HelperManager.class);
startActivity(showHelper); ?
I have tried the 2nd line (AssetManager am = ...) with and without the getApplicationContext() bit, tried moving the file into a subfolder of /assets and tried files = am.list("") with leading and trailing slashes. If I use a subfolder the files array is empty when the code runs (set a breakpoint on the files = am.list(""); line and inspected it at run time.
The strange thing is that it worked once - when I first wrote the code, but for further testing, I deleted the file from the /sdcard folder on the phone, and it never worked since even though the file is still in the assets folder.
I am using Android Studio if that matters.
Thanks
Managed to get a solution using Load a simple text file in Android Studio as a fix. It still puts the 4 folders in the files array but I Can skip them using code as given above, although I should rather check for the file I want rather than the 4 I don't!

Managing text files Android

I've got a little problem while managing .txt files on Android. I've found this link (it's in Spanish) that explains how to use text files on my Android device.
What I want to do, is create a text file using the intern memory of the device, as I don't want the user depend on a SD card, and a raw text file won't allow me to write on in, only read. So I want a text file that can append some information and, in a particular case, delete all the content in the text file and reset it.
I've written this code for the writing side:
OutputStreamWriter fout = null;
try
{
fout = new OutputStreamWriter(openFileOutput("measures.txt", Context.MODE_APPEND));
fout.write(measure);
}
catch (Exception ex)
{
Log.e("Files", "Error while opening to write file measures.txt");
}
finally
{
try
{
fout.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I guess this part opens the file "measure.txt" in the APPEND mode, or creates it in APPEND mode.
When I try to read from it:
BufferedReader fin = null;
try
{
fin = new BufferedReader(new InputStreamReader(context.openFileInput("medidas.txt")));
String line = fin.readLine();
// Some staff with this line
fin.close()
}
// catch staff
What I want to do is delete all the content in the text file before I close the file. The idea is store the information in another type of variable, and then, when I finish reading from file, reset the content.
How can I do that?
Ok, I solved my problem doing this:
deleteFile("measures.txt");
And that will [i]erase[/i] for sure the file... :P

Android: Storing Image into project directory (files)?

I want to store my Bitmap image into project directory. How can I have access to my project folder or what is the address of my project folder?
You have to put the images in the res/drawable folder. Then, you can access them by using: R.drawable.name_of_image (for name_of_image.png or name_of_image.jpg).
If you want to access them by their original name, you better save them in the assets folder. Then, you can access them by using the AssetManager:
AssetManager am = getResources().getAssets();
try {
InputStream is = am.open("image.png");
// use the input stream as you want
} catch (IOException e) {
e.printStackTrace();
}
If you want to save a programatically created image, you can do:
try {
FileOutputStream out = new FileOutputStream(context.getFilesDir().getAbsolutePath()+"/imagename.png");
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
You can't save it to your project directory. I recommend you to read the documentation about how android packages work, because it seems you don't understand.

How to write files to assets folder or raw folder in android?

I am working on some application where I have to update some files present in assets / raw folder runtime from some http location.
Can anyone help me to by sharing how to write files in assets or raw folder?
It cannot be done. It is impossible.
Why not update the files on the local file system instead?
You can read/write files into your applications sandboxed area.
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Other alternatives you may want to look into are Shared Perferences and using Cache Files (all described at the link above)
You cannot write data's to asset/Raw folder, since it is packed(.apk) and not expandable in size.
If your application need to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).
Another approach for same issue may help you
Read and write file in private context of application
String NOTE = "note.txt";
private void writeToFile() {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(
NOTES, 0));
out.write("testing");
out.close();
}
catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
}
}
private void ReadFromFile()
{
try {
InputStream in = openFileInput(NOTES);
if (in != null) {
InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuffer buf = new StringBuffer();
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
in.close();
String temp = "Not Working";
temp = buf.toString();
Toast.makeText(this, temp, Toast.LENGTH_SHORT).show();
}
} catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), 2000).show();
}
}
You Can't write JSON file while in assets. as already described assets are read-only. But you can copy assets (json file/anything else in assets ) to local storage of mobile and then edit(write/read) from local storage. More storage options like shared Preference(for small data) and sqlite database(for large data) are available.

Categories

Resources