Android path to asset txt file
AssetFileDescriptor descriptor = getAssets().openFd("myfile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());
Try using the above with FileDescriptors. Seems to be the most foolproof way I've found to gather asset paths.
How to specify path to read a .txt file in assets directory
Files in assets/
cannot be accessed using the File class. Use context.assets
to get the AssetManager, and you can open InputStreams to the files.
Save a (.txt) file to the Assets Folder in Android?
You can't. The assets folder is read-only at runtime.
Pick a different location to save your data, see Data Storage for more information.
read file from assets
Here is what I do in an activity for buffered reading extend/modify to match your needs
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
EDIT : My answer is perhaps useless if your question is on how to do it outside of an activity. If your question is simply how to read a file from asset then the answer is above.
UPDATE :
To open a file specifying the type simply add the type in the InputStreamReader call as follow.
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
EDIT
As @Stan says in the comment, the code I am giving is not summing up lines. mLine
is replaced every pass. That's why I wrote //process line
. I assume the file contains some sort of data (i.e a contact list) and each line should be processed separately.
In case you simply want to load the file without any kind of processing you will have to sum up mLine
at each pass using StringBuilder()
and appending each pass.
ANOTHER EDIT
According to the comment of @Vincent I added the finally
block.
Also note that in Java 7 and upper you can use try-with-resources
to use the AutoCloseable
and Closeable
features of recent Java.
CONTEXT
In a comment @LunarWatcher points out that getAssets()
is a class
in context
. So, if you call it outside of an activity
you need to refer to it and pass the context instance to the activity.
ContextInstance.getAssets();
This is explained in the answer of @Maneesh. So if this is useful to you upvote his answer because that's him who pointed that out.
How to access a file from asset/raw directory
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);
How to get URI from an asset File?
There is no "absolute path for a file existing in the asset folder". The content of your project's assets/
folder are packaged in the APK file. Use an AssetManager
object to get an InputStream
on an asset.
For WebView
, you can use the file
Uri
scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/...
(note: three slashes) where the ellipsis is the path of the file from within the assets/
folder.
get the names of txt files from assets folder into a list
it should be
String[] files = assetManager.list("");
if you want to get what's inside a subfolder pass the name of the subfolder:
String[] files = assetManager.list("mySubFolder");
How to get the android Path string to a file on Assets folder?
AFAIK the files in the assets directory don't get unpacked.
Instead, they are read directly from the APK (ZIP) file.
So, you really can't make stuff that expects a file accept an asset 'file'.
Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:
File f = new File(getCacheDir()+"/m1.map");
if (!f.exists()) try {
InputStream is = getAssets().open("m1.map");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
mapView.setMapFile(f.getPath());
What is the best approach to open a TXT file from assets and read a string?
You can just handle the exception properly when the file isn't found like this :
try {
InputStream is = SplashscreenActivity.this.getAssets().open("yourTextFile.txt");
} catch (IOException e) {
// catch your exception properly when the file isn't found
}
Related Topics
Flutter Does Not Find Android Sdk
Add a Search Filter on Recyclerview with Cards
Android Studio:Failure [Install_Failed_Older_Sdk]
Libpng Error: Not a Png File Error Showing in Android Studio
Differencebetween @Id and @+Id
Adb Connection by Wifi Getting Killed When a New Usb Attached/Detached
Disable Logcat Output Completely in Release Android App
Android SQLite: Update Statement
Android: How Do Bluetooth Uuids Work
The Process of the Service Is Killed After the Application Is Removed from the Application Tray
How to Repeat a Method Every 10 Minutes After a Button Press and End It on Another Button Press
Android Cannot Pass Intent Extras Though Alarmmanager
How to Fix: "You Need to Use a Theme.Appcompat Theme (Or Descendant) with This Activity"
Android Play Services 6.5: Locationclient Is Missing