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");
Related
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");
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'm quite new to android programming and I have the following problem.
I want to be able to put an image om my server and then if I use my app it should use that image as a background.
From previous research I understand I cant save any files to the drawable file?
So is this even possible?
I am now this far:
URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
InputStream input = url.openStream();
try {
String storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/oranjelangb.png");
try {
byte[] buffer = new byte[1000000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
But I get the following error
# String storagePath = Environment.getExternalStorageDirectory();
The compiller says cannot convert file to string.
It should be possible. Simple steps may include :-
1) Download image file from server, Store it to SDcard or assets folder.
links for step 1 >> link1 link2
2) Create a Bitmap from the file you downloaded.
3) Set that bitmap as a Background image.
You can pick steps and search on SO there should be lots of answers available.
I have a text file in the assets folder that I need to turn into a File object (not into InputStream). When I tried this, I got "no such file" exception:
String path = "file:///android_asset/datafile.txt";
URL url = new URL(path);
File file = new File(url.toURI()); // Get exception here
Can I modify this to get it to work?
By the way, I sort of tried to "code by example" looking at the following piece of code elsewhere in my project that references an HTML file in the assets folder
public static Dialog doDialog(final Context context) {
WebView wv = new WebView(context);
wv.loadUrl("file:///android_asset/help/index.html");
I do admit that I don't fully understand the above mechanism so it's possible that what I am trying to do can't work.
Thx!
You cannot get a File object directly from an asset, because the asset is not stored as a file. You will need to copy the asset to a file, then get a File object on your copy.
You cannot get a File object directly from an asset.
First, get an inputStream from your asset using for example AssetManager#open
Then copy the inputStream :
public static void writeBytesToFile(InputStream is, File file) throws IOException{
FileOutputStream fos = null;
try {
byte[] data = new byte[2048];
int nbread = 0;
fos = new FileOutputStream(file);
while((nbread=is.read(data))>-1){
fos.write(data,0,nbread);
}
}
catch (Exception ex) {
logger.error("Exception",ex);
}
finally{
if (fos!=null){
fos.close();
}
}
}
Contrary to what others say, you can obtain a File object from an asset as follows:
File myAsset = new File("android.resource://com.mycompany.app/assets/my-asset.txt");
This function missing in code. #wadali
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Source: https://stackoverflow.com/a/4530294/4933464
I am currently trying to figure out a way to write a media file to internal/external storage (primary storage). The file to be saved could be any size from a few MBs to 50MBs. I have logic that works on my Droid X 2.3.3 Razr 2.3.5 (I believe) but does not work on my Galaxy Nexus (has no removable storage but a built in 16Gig card with v4.0.2). I have looked around and haven't found any code/samples that work with v4.0. Maybe I am approaching this all wrong since it doesn't have an actual sd card? maybe it is something new in v4.0? Currently when I run my application on the Galaxy Nexus I get this: System.err(19520): java.io.FileNotFoundException:
UPDATED
InputStream inputStream = urlConnection.getInputStream();
File PATH = Environment.getExternalStorageDirectory();
File FILE = new File(Environment.getExternalStorageDirectory()+ "/" + FILENAME);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// buffer int bufferSize = 1024; int bufferLength = 0; byte[] buffer = new byte[bufferSize];
while ((bufferLength = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, bufferLength);
}
byte[] temp = byteBuffer.toByteArray();
FileOutputStream fos = new FileOutputStream(FILE);
fos.write(temp);
fos.close();
Are you putting this file in a specific directory on your sdcard?external storage?
I assume your permissions in your manifest are good because the 'permission denied is not raised' so maybe if you put the file in a specific folder, which is not created you should call the mkdirs() function on your file!
First, don't convert it to a string, just use getExternalStorageDirectory() as a File:
File sd = Environment.getExternalStorageDirectory();
File file = new File(sd, FILENAME);
I don't know if that will correct it or not, but it wouldn't hurt to try that. And you do not need to call file.createNewFile() before writing to the file with a FileOutputStream. The docs about FileOutputStream say:
An output stream that writes bytes to a file. If the output file
exists, it can be replaced or appended to. If it does not exist, a new
file will be created.
And which line of code is the FileNotFoundException happening on?