-->

Where should I save my file in Android for local a

2020-06-30 03:35发布

问题:

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