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

こ雲淡風輕ζ 提交于 2019-12-05 07:42:56

问题


I have two datasets which are currently in the same folder as my java files AND on my PC. Currently, I am accessing them through my C-drive. Since this is an app, where should I save my .ARFF files and what path should I use instead? I have tried in the raw folder, but nothing seems to work.

Here's what I have so far...


回答1:


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();
}
}



回答2:


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:

  • https://inducesmile.com/android-programming/how-to-read-a-file-from-raw-directory-in-android/
  • https://gist.github.com/Airfixed/799e784696b0a60c5423d347bf33a341


来源:https://stackoverflow.com/questions/55448528/where-should-i-save-my-file-in-android-for-local-access

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