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");
Related
I am trying to program a simple todo app for my android phone. Ive gotten far enough that I would like to save these strings that I input. However, every time I try to write the data I get a file not found exception. Here is the code I use in my onCreate method to instantiate the File.
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
I then have two methods, one to write to the File, and the other to read from it. They look like this:`
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader("Todo_File.txt"));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
and
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter("Todo_File.txt"));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
items is a stringArray which holds the strings that were input. Every time that I try to write or read the files I get the following exception:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
I don't understand why Android Studio cant find the file that I created, can anyone help?
You are looking for a file "Todo_File.txt".
Where have you kept this file?
Are you keeping it as a resource file in the "res/raw" directory of your app or it is lying somewhere in the phone storage?
Here you can get some idea of types of the storage
https://developer.android.com/guide/topics/data/data-storage.html
https://android.stackexchange.com/questions/112951/two-types-of-internal-storage-what-is-the-difference
Mostly likely I guess you need to correct the path of this file.
here are the way to get the "/storage/sdcard0/" path
Environment.getExternalStorageDirectory()
The standard way to do File-IO in Android is using the context-relevant IO-methods.
To write a file, use the following code. Details about the different file-modes are available here.
FileOutputStream fOut = openFileOutput("Todo_File.txt", MODE_WORLD_READABLE);
To read a file, use this:
FileInputStream fIn = openFileInput("Todo_File.txt");
Since you defined
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
you can do:
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader(itemFile));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(itemFile));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
You need to actually create the file before you write to it. You should do something like this:
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}
What you have done is simply tried to read from the file. The fact that you get the error:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
Is an indication that the file you want to write to hasn't been created, and I don't see you creating the file anywhere.
If you are using an emulator, you need to make sure that you have an SDK card set up on your device, and then do:
File itemFile = new File(Environment.getExternalStorageDirectory(),"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}
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.
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!
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
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");