Where should I save my file in Android for local access?

风流意气都作罢 提交于 2019-12-03 21:51:33

Create a raw directory in your project, raw is included in the res folder of android project. You can add an assets files in raw folder like music files, database files or text files or some other files which you need to access directly

1) Right click on res folder, select New> Directory, then studio will open a dialog box and it will ask you to enter the name.

2) Enter “raw” and click OK. Open res folder and you will find your raw folder under it.

InputStream input = Context.getResources().openRawResource(R.raw.your_file_name);

// Example to read file from raw directory

private String readFileFromRawDirectory(int resourceId)
{
InputStream iStream = context.getResources().openRawResource(resourceId);
ByteArrayOutputStream byteStream = null;
try {
byte[] buffer = new byte[iStream.available()];
iStream.read(buffer);
byteStream = new ByteArrayOutputStream();
byteStream.write(buffer);
byteStream.close();
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteStream.toString();
}
}

After too many hours

A very easy solution to retrieving data from the assets folder! Only one user-defined method.

  1. Make raw folder in res directory.
  2. Paste whatever files in the raw directory
  3. Make a separate .java file
  4. Make sure it is a derivative class (in this case it extended AppCompatActivity
  5. Write Part A in the body
  6. Write Part B outside the body

A. This is in the main function OR in a custom, user-defined function.

BufferedReader bReader;            
bReader = new BufferedReader(
           new InputStreamReader(ISR(R.raw.FILENAME_WITHOUT_TYPE)));

FILENAME_WITHOUT_TYPE refers to only the name of the file, not its ending (everything followed by the .).

B. This is the definition of ISR.

public InputStream ISR(int resourceId) {
    InputStream iStream = getBaseContext().getResources().openRawResource(resourceId);
    return iStream;
}

Works like a charm!

Resources:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!