What is the path to a file located in the raw folder in android studio?

2

I would like to get the path to the file "datos.txt" located in the folder "raw" in "res", in Windows it would be something similar to "app / res / raw / data", but I can not get it to work.

I've already tried it with the String path = "android.resource://" + getPackageName() + "/" + R.raw.datos; but when I create a File object with the path, its exists() method returns false and jumps an exception.

I would like to save the file as a File object to pass it through RandomAccessFile, so I can not either InputStream arquivo = getResources().openRawResource(R.raw.datos);

Thanks in advance, greetings

    
asked by Bugzilla 26.08.2018 в 23:03
source

1 answer

1

There is no path as such, you can actually get the Uri where the file is located within your /raw directory:

 Uri archivo = Uri.parse("android.resource://" + getPackageName() + "/raw/myFile");

and from this Uri get File :

   File file = new File(archivo.getPath());
    if(file.exists()){
        Log.i("Archivo", "file existe! ");
    }else{
        Log.i("Archivo", "No existe! ");
    }

You can also get the InputStream you can get using openRawResource() :

InputStream inputStream = getResources().openRawResource(R.raw.myFile);

When you get InputStream you can use this method to create a file:

private void copyInputStreamToFile(InputStream in, File file) {
    OutputStream out = null;

    try {
        out = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while((len=in.read(buf))>0){
            out.write(buf,0,len);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        // Ensure that the InputStreams are closed even if there's an exception.
        try {
            if ( out != null ) {
                out.close();
            }

            in.close();
        }
        catch ( IOException e ) {
            e.printStackTrace();
        }
    }
}

In this way you can create a file from InputStream

 InputStream inputStream = getResources().openRawResource(R.raw.myFile);
 String pathFile = Environment.getExternalStorageDirectory()+ "/Android/data/nuevo_archivo.txt";
 copyInputStreamToFile(arq, new File(pathFile));
    
answered by 27.08.2018 / 16:09
source