Get Assets folder path and read txt file to string Android example code

Programmatically load text from Asset folder file myData.txt to string Android example source code.
Read file to byte[] buffer and convert into string Android example.
Assets folder path may be: c:\documents\_android_projects\MyProject\assets

           // Path for a WebView
String sAssets = "file:///android_asset/" + "index.htm";
WebView mWebView = (WebView)findViewById(R.id.webview1);
mWebView.loadUrl(sAssets);
           // Path to Assets folder Context.getAssets
           // getContext().getAssets()
           // getAssets() - Return an AssetManager instance for your application's package.
 
//  File file = new File(getAssets()+"myFileName.txt"); // Error
 
            // file to inputstream
            InputStream input = getAssets().open("myData.txt");
            // myData.txt can't be more than 2 gigs.
            int size = input.available();
            byte[] buffer = new byte[size];
            input.read(buffer);
            input.close();
 
            // byte buffer into a string
            String text = new String(buffer);
This entry was posted in Android Examples Code and tagged , , , , , , . Bookmark the permalink.


Comments are closed.

55,365 views