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.
Related
I have a config.json file in the asset folder in my application. Now the scenario is, I will pull a JSON content from server and will update(override) the config.json file stored in asset folder. How can I achieve this? Here is sample of JSON:
{
"id": 1,
"name": "A green door",
"price": 12.50,
"tags": ["home", "green"]
}
I am able to read the file from the asset folder. But how to write in that file?:
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("config.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
You can't write to asset folder. because it's a read-only folder. Instead, you need to save the file to your app folder. Whenever you want to use the config, check if the file is existed in your app folder. if it's exist, use it, if not, use the default one.
For example, when you get the config.json, save the file:
String filename = "config.json";
String fileContents = "Your config content..";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Then, whenever you want to use, read it:
File file = new File(context.getFilesDir(), "config.json");
String config = "";
if(file.exists()) {
// use the config.
} else {
// use the config from asset.
}
Read more at Save Files on Device Storage for saving the file.
Whatever the files we keep in assets folder, it can not be modified at run time. Within an APK, files are read-only. Neither we can delete nor we can create any files within this directory.
What you can do is write your new JSON to a file (e.g., getFilesDir())
As this answers suggests
You cannot write data to asset/Raw folder, since it is packed(.apk) and not expandable in size.
check here
with this below code i'm trying to access the file which is stored in asset/raw folder, but getting null and
E/ERR: file:/android_asset/raw/default_book.txt (No such file or directory)
error, my code is:
private void implementingDefaultBook() {
String filePath = Uri.parse("file:///android_asset/raw/default_book.txt").toString();
File file = new File(filePath);
try {
FileInputStream stream = new FileInputStream(file);
} catch (Exception e) {
e.printStackTrace();
Log.e("ERR ", e.getMessage());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
Place your text file in the /assets directory under the Android project and use AssetManager class as follows to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("default_book.txt");
Or you can also put the file in the /res/raw directory, from where the file can be accessed by an id as follows
InputStream is =
context.getResources().openRawResource(R.raw.default_book);
Assets and resources are files on your development machine. They are not files on the device.
For assets, use open() on AssetManager to get an InputStream on your asset.
Also, FWIW:
Uri.parse("file:///android_asset/raw/default_book.txt").toString() is pointless, as it gives you the same string that you started with
file:///android_asset/ only works for WebView
As the actual question wasn't sufficiently answered, here we go
InputStream is = context.getAssets().openFd("raw/"+"filename.txt")
context can be this or getActivity() or basically any other context
Important is to include the folder before the filename separated by an /
In Kotlin we can achieve as-
val string = requireContext().assets.open("default_book.txt").bufferedReader().use {
it.readText()
}
InputStream is = getAssets().open("default_book.txt");
I have an index.html file and some images displayed on this page stored in res/raw folder.
I need to open this file in android browser. So, I copy this file into sdcard.
But if i use R.raw.index the index file only copied other files are not copied.
Since other html and images are not copied to sdcard: I don't see the images when I open index.html in browser.
Here is my current code to copy raw resource:
private File copyFile(int resourceId, String filename) {
InputStream in = null;
OutputStream out = null;
File outFile = null;
try {
in = mContext.getResources().openRawResource(resourceId);
outFile = new File(mContext.getExternalFilesDir(null), filename);
Log.d("TestHTML", "output file" + outFile.getAbsolutePath());
out = new FileOutputStream(outFile);
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
} catch(IOException e) {
Log.e("TestHTML", "Failed to copy file", e);
} finally {
try {
in.close();
out.flush();
out.close();
in = null;
out = null;
} catch (Exception e){}
}
return outFile;
}
And here is the layout of the res/raw folder
Can you give me a hint on how to copy the whole content of the res/raw directory to the internal storage ?
From the android doc about the res/raw folder:
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.
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.
Since you will use all this stuff in html : you need to keep an access by filename. So don't put those files in res/raw. Put them in your assets folder.
Once this is done you can copy all of them one by one and recursively to to internal storage.
The entry point to list files in some assets folder is getAssets().list(path) where path denote the path to the directory containing the index.html.
You also have to update your copyFile method to make it recursive and listing files from assets.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Android - How to determine the Absolute path for specific file from Assets?
I am trying to pass a file to File(String path) class. Is there a way to find absolute path of the file in assets folder and pass it to File(). I tried file:///android_asset/myfoldername/myfilename as path string but it didnt work. Any idea?
AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.
But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).
Try to do something like:
AssetManager am = getAssets();
InputStream inputStream = am.open("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;
}
Let me know about your progress.
Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
You'll need to unpack the file or use it directly.
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename"); to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
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