The code below works: it reads a file named "file.txt" which is located in the "assets" folder of the APK and stores it in a buffer. So far, so good:
String u = "content://com.example.app/file.txt:assets"
ContentResolver r = controls.activity.getContentResolver();
InputStream in = r.openInputStream(Uri.parse(u));
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = in.read(buffer);
while (n >= 0) {
out.write(buffer, 0, n);
n = in.read(buffer);
}
in.close();
return out.toByteArray();
If however the file I want to read is in a subfolder of assets, e.g. subfolder "sub", and I provide this Uri to the above code:
String u = "content://com.example.app/sub/file.txt:assets"
... then in this case I don't get anything. The file is there, as assets/sub/file.txt but the above code returns an empty buffer. The only change I made is to replace "file.txt" with "sub/file.txt" which points to where the file is stored.
What am I doing wrong? Is it wrong to create the uri string manually like that? I believe it's allowed to store files in assets subfolders... If that's allowed, how do I specify the path in the uri string?
Note that I'm not trying to give access to the file to another app, I just want to read my own file from my own APK's assets and put it in a buffer for internal use.
Any help is greatly appreciated!
Use AssetManager and its open() method. So, you would replace:
ContentResolver r = controls.activity.getContentResolver();
InputStream in = r.openInputStream(Uri.parse(u));
with:
AssetManager assets = controls.activity.getAssets();
InputStream in = assets.open("sub/file.txt");
Related
I have been using this tutorial to make some face detections on picture. The problem is when I getting the file path that used on java
String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);
How can I translate on android studio. I try put my lbpcascade_frontalface.xml on raw resources. CascadeClassifier is a class that opencv library provided. The only problem is they only loaded string path (on xmlfile).
this is my code.
String pathtoRes = getRawPathAtempt2(context);
CascadeClassifier cascadeClassifier = new CascadeClassifier();
cascadeClassifier.load(pathtoRes);
I translated to some method like this.
public String getRawPathAtempt2(Context context) {
return "android.resource://" + context.getPackageName() + "/raw/" + "lbpcascade_frontalface.xml";
}
I get the asertions error by opencv that tell me the file is null. Thats mean I had been wrong when I used file path on my method. how can I get file path on raw resources? help me please I have been stuck for several days now
how can i get file path on raw resources?
You can't. There is no path. It is a file on your development machine. It is not a file on the device. Instead, it is an entry in the APK file that is your app on the device.
If your library supports an InputStream instead of a filesystem path, getResources().openRawResource() on a Context to get an InputStream on your raw resource.
This is how i solved the problem with #CommonWare Answer
i'm using input stream to get file
is = context.getResources().openRawResource(R.raw.lbpcascade_frontalface);
so make the file will be opened and i will make a point to the File class
File cascadeDir = context.getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
and then i make a search to the path file using getAbsolutePath like this
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
take a look at my full code
try {
is = context.getResources().openRawResource(R.raw.lbpcascade_frontalface);
File cascadeDir = context.getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
} catch (IOException e) {
Log.i(TAG, "face cascade not found");
}
Uri video = Uri.parse("android.resource://com.test.test/raw/filename");
Using this you can access the file in raw folder, if you want to access the file in asset folder use this URL...
file:///android_asset/filename
Make sure you don't add the extension to the filename. E.g. "/movie" not "/movie.mp4".
Refer to this link:
Raw folder url path?
We can use this Alternative method for finding the path of Files in Raw Folder.
InputStream inputStreamdat=getResources().openRawResource(R.raw.face_landmark_model);
File model=getDir("model", Context.MODE_PRIVATE);
File modelFile=new
File(model,"face_landmark_model.dat");
FileOutputStream os1 = new
FileOutputStream(modelFile);
byte[] buffer1 = new byte[4096];
int bytesRead1;
while ((bytesRead1=inputStreamdat.read(buffer1))!=-1) {
os1.write(buffer1, 0, bytesRead1);
}
inputStreamdat.close();
os1.close();
You Can Use
modelFile.getAbsolutePath()); For getting the Path
I want to open a file from the folder res/raw/.
I am absolutely sure that the file exists.
To open the file I have tried
File ddd = new File("res/raw/example.png");
The command
ddd.exists();
yields FALSE. So this method does not work.
Trying
MyContext.getAssets().open("example.png");
ends up in an exception with getMessage() "null".
Simply using
R.raw.example
is not possible because the filename is only known during runtime as a string.
Why is it so difficult to access a file in the folder /res/raw/ ?
With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName());
To get it as a InputStream
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
Here is example of taking XML file from raw folder:
InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML
Then you can:
String sxml = readTextFile(XmlFileInputStream);
when:
public String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).
BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.
Here are two approaches you can read raw resources using Kotlin.
You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.
Cheers mate 🎉
// R.raw.data_post
this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)
I have a file myfile.vtpk in my application's "Assets" folder.
I'm trying to load this file file in my application using the following:
Uri vtpkUri = new Uri("file:///android_asset/myfile.vtpk");
ArcGISVectorTiledLayer vtpkLayer = new ArcGISVectorTiledLayer(vtpkUri);
MyMapView.Map.OperationalLayers.Add(vtpkLayer);
I get no error, but the file is never loaded.
How can I access this file in Android?
Thanks!
Since a file in your Assets folder is compiled into your APK, there is no "Uri" for a file in your assets folder, or any file in your APK for that matter. If you need to be able to pass a Uri, you would want to copy the Asset to your Document or other folder for your app and then get the Uri.
First create a method to take an read stream and write write stream and write your asset to a file:
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
Then get the read stream from the asset:
AssetFileDescriptor afd = Assets.OpenFd("filenameinAssetsfolder.ext");
var readStream = afd.CreateOutputStream();
Then create the path for the file and the write stream:
// This will be your final file path
var pathToWriteFile =
Path.Combine (System.Environment.GetFolderPath
(System.Environment.SpecialFolder.Personal),
"filenametowrite.ext");
FileStream writeStream =
new FileStream(pathToWriteFile,
FileMode.OpenOrCreate,
FileAccess.Write);
And finally call the copy method created above:
ReadWriteStream(readStream, writeStream);
Now you should be able to access the file with the path in pathToWriteFile.
EDIT: As per the comment below, try the following instead of getting an AssetFileDescriptor first. Replace:
AssetFileDescriptor afd = Assets.OpenFd("filenameinAssetsfolder.ext");
var readStream = afd.CreateOutputStream();
with:
Stream readStream = Assets.Open("filenameinAssetsfolder.ext");
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Android - How to determine the Absolute path for specific file from Assets?
I am trying to pass a file to File(String path) class. Is there a way to find absolute path of the file in assets folder and pass it to File(). I tried file:///android_asset/myfoldername/myfilename as path string but it didnt work. Any idea?
AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.
But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).
Try to do something like:
AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
Let me know about your progress.
Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
You'll need to unpack the file or use it directly.
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename"); to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
How can you read GZIP file in Android located in the "ASSETS" (or resources/raw) folder?
I have tried the following code, but my stream size is always 1.
GZIPInputStream fIn = new GZIPInputStream(mContext.getResources().openRawResource(R.raw.myfilegz));
int size = fIn.available();
for some reason the size is always 1. But if Idon't GZIP the file, it works fine.
NOTE:
Using Android 1.5
I met the same problem when reading a gz file from assets folder.
It's caused by the file name of the gz file. Just renaming yourfile.gz to other name like yourfile.bin. It seems Android build system would decompress a file automatically if it thought it's a gz.
public class ResLoader {
/**
* #param res
* #throws IOException
* #throws FileNotFoundException
* #throws IOException
*/
static void unpackResources() throws FileNotFoundException, IOException {
final int BUFFER = 8192;
android.content.res.Resources t = TestingE3d.mContext.getResources();
InputStream fis = t.openRawResource(R.raw.resources);
if (fis == null)
return;
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis,
BUFFER));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
int count;
FileOutputStream fos = TestingE3d.mContext.openFileOutput(entry
.getName(), 0);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
byte data[] = new byte[BUFFER];
while ((count = zin.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
// Log.v("NOTAG", "writing "+count + " to "+entry.getName());
}
dest.flush();
dest.close();
}
zin.close();
}
}
R.raw.resources is a zip file - this class will decompress all files in that zip to your local folder.
I use this for NDK.
you can access your fils from ndk through:
/data/data//files/
package = package where ResLoader resides
filename = one of files that is in raw/resources.zip
this is the documented behavior of InflaterInputStream.available:
http://java.sun.com/javase/6/docs/api/java/util/zip/InflaterInputStream.html#available()
Returns 0 after EOF has been reached, otherwise always return 1.
abusing available is a common mistake --- in no case can you assume that it tells you the length of a file (though it sometimes happens to do so, as you've noticed). you want to keep calling read(byte[], int, int) until it returns 0. if you want the length to allocate a byte[] up front, you probably want to create a ByteArrayOutputStream and write to that each time you read, and then get a byte[] from that when you exit the loop. this works for all InputStreams in all cases.
It seems that the build system treats .gz files as a special case, even when it's included as a raw resource. Rename the .gz file to have a different extension, say .raw or .bin .
Valid at least for Android Studio 2.2 . I can't find any docs to confirm this is expected behaviour or, better, how to prevent it, but changing the extension at least works around the problem.
What happens if you use AssetManager instead of Resources? Example:
InputStream is = mContext.getAssets().open("myfilegz");
GZIPInputStream fIn = new GZIPINputStream(is);
Internally, Resources is just calling AssetManager; I wonder if somewhere along the way it musses things up.
Try looking at the source for Translate from apps-for-android open source project and see if that helps at all.
They use GZIPInputStream on a raw file in their selectRandomWord() function [line 326] (source pasted below)
public void selectRandomWord() {
BufferedReader fr = null;
try {
GZIPInputStream is =
new GZIPInputStream(getResources().openRawResource(R.raw.dictionary));