Ok, so far all the answers I've found seem to be answered to by people who do not know the answer...
This should be a simple one (free rep for you yay):
I have a file in res/raw/ called overworld_a.tmx
I need to load it using the path as a string then the filename added to the string, since it varies.
Like so:
String mapName = "overworld_a.tmx";
try {
TMXMapReader mapReader = new TMXMapReader();
map = mapReader.readMap("raw/"+mapName);
} catch (Exception e) {
System.out.println("Error while reading the map:\n" + e.getMessage());
return;
}
Problem is, this obviously doesn't work.... Simple Question is, what is the relative path to that file?
And if this is not a possibility:
Complex question is, how do I open varying files from res folder and its children?
You can read overworld_a.tmx from res/raw dir as :
1. use openRawResource for reading overworld_a.tmx as InputStream from raw folder :
String mapName = "overworld_a"; //<< just pass name without file extension
resID = getResources().getIdentifier(mapName, "raw", getPackageName());
InputStream inputStream = getResources().openRawResource(resID);
2. Get ByteArrayOutputStream from inputStream :
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//... your code for reading byteArray from inputStream
3. Pass byteArrayOutputStream to mapReader.readMap :
TMXMapReader mapReader = new TMXMapReader();
map = mapReader.readMap(byteArrayOutputStream);
//.....
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 am trying to open a file located within my android studio project # res/drawable/conan_obrian.png. However, a java.io.FileNotFoundException was thrown. I have tried different pathname combinations with no results.
this snippet is throwing the exception:
InputStream is;
byte[] buffer = new byte[0];
try {
final AssetManager assetMgr = context.getResources().getAssets();
is = assetMgr.open("drawable/conan_obrian.png");
buffer = new byte[is.available()];
is.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
serverAPI.register(userName, Base64.encodeToString(buffer,Base64.DEFAULT).trim(), myCrypto.getPublicKeyString());
Your code would be correct if you had an assets/drawable folder, but you are trying to load a resource, so that would be R.drawable.conan_obrian.
You can use that id to setResourceDrawable on an ImageView, for example.
Or you can get a Drawable object using that ID with
Drawable d = getResources().getDrawable(R.drawable.conan_obrian)
Anything under the res/ directory gets loaded into a long list of integers in the R.java file.
Android Studio 0.8.1
Hello,
I have created a keystore called snapzkeystore.bks using the keytool. I want to get the path so I can pass it to a function and load it. However, I can’t seem to get the path. I have also tried putting it in the raw and assets folder and trying to get it that way and testing what works, However, I also get a FileNotFoundException calling this function keyStoreFile.load(fileInputStream, password) (code below)
Trying to get it when put in the raw folder Test 1:
String uri = "android.resource://" + getActivity().getPackageName() + "/" + R.raw.snapzkeystore;
snapClient.makeRequest(uri.toString());
I get FileNotFoundException Exception and the and the string contains:
android.resource://com.sunsystem.snapzui/2131034112
I have also tried using the assets folder and using this instead Test 2:
Resources resources = getResources();
InputStream inputStream;
try {
inputStream = resources.getAssets().open("snapzkeystore.bks");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(buffer);
byteArrayOutputStream.close();
inputStream.close();
Log.d(TAG, "asset: " + inputStream.toString());
snapClient.makeRequest(inputStream.toString());
} catch (IOException e) {
Log.d(TAG, "IOException: " + e.getMessage());
}
I get FileNotFoundException Exception and the and the string contains:
android.content.res.AssetManager$AssetInputStream#5363f738
Source snippet for loading the keystore:
public int makeRequest(String keyStoreFileName) {
try {
KeyStore keyStoreFile = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream fileInputStream = new FileInputStream(keyStoreFileName);
// FileNotFoundException
keyStoreFile.load(fileInputStream, password);
Just a quick questions, which is the best folder to put a keystore in, raw or assets?
Many thanks in advance for any suggestions
I want to get the path so I can pass it to a function and load it. However, I can’t seem to get the path
That is because there is no path. Those are not files. They are entries in the APK file.
I get FileNotFoundException Exception and the and the string contains: android.content.res.AssetManager$AssetInputStream#5363f738
That is because you called toString() on an InputStream returned from the AssetManager.
Source snippet for loading the keystore
load() takes an InputStream. You do not have to use a FileInputStream. You are welcome to pass the InputStream that you get from the AssetManager to load():
KeyStore keyStoreFile = KeyStore.getInstance(KeyStore.getDefaultType());
keyStoreFile.load(resources.getAssets().open("snapzkeystore.bks"), password);
Just a quick questions, which is the best folder to put a keystore in, raw or assets?
Either should be fine. You can use openRawResource() on Resources, IIRC, to get an InputStream on a raw resource.
Hi I want to show an image from SD card. I have 10 images. out of which i am able to show 9 images but 1 image i cannot show in image view.
My SD card location is correct. I am using android programming. I am getting file exists as true. also I am getting not null input stream but when I want to get Drawable object for some fiels i am not getting but for all others getting drawable object.
Also I have tried using
iv1.setImageURI(Uri.parse(str1))
but i didnot get any solution
Following is my code snippet
InputStream is1 = getBitMapImage(str1);
InputStream is2 = getBitMapImage(str2);
InputStream is3 = getBitMapImage(str3);
Drawable d1 = Drawable.createFromStream(is1, "first");
Drawable d2 = Drawable.createFromStream(is2, "second");
Drawable d3 = Drawable.createFromStream(is3, "third");
iv1.setImageDrawable(d1);
iv2.setImageDrawable(d2);
iv3.setImageDrawable(d3);
System.out.println(is1+"....d1...."+d1);
System.out.println(is2+"....d2...."+d2);
System.out.println(is3+"....d3...."+d3);
public static BufferedInputStream getBitMapImage(String filePath) {
Log.e("Utilities", "Original path of image from Utilities "+filePath);
File imageFile = null;
FileInputStream fileInputStream = null;
BufferedInputStream buf= null;
try{
imageFile= new File(filePath);
System.out.println("Does Images File exist ..."+imageFile.exists());
fileInputStream = new FileInputStream(filePath);
buf = new BufferedInputStream(fileInputStream);
}catch(Exception ex){
}finally{
try{
imageFile = null;
fileInputStream.reset();
fileInputStream.close();
}catch(Exception ex){}
}
return buf;
}
Some image files cannot be shared. Blackbery rem file cannot be shared. That type of file cannot be opened if stored directly. So during storing convert that file into .jpg file and then only u can open those file. For checking purpose pullout your file from the device to your system then convert in into .jpg file using gimp and push into device once again then try to run your program and check whether your image file is diplayed in your image view.
Thanks
Sunil