Opening Android resource file by URI raises FileNotFoundException - java

I am trying to get a URI to a resource in my res/raw/ directory. The goal is to give this URI to a VideoView, but this has been problematic, and I seem to be unable to open the file with test code.
I have the following test code:
String uri = "android.resource://com.my.package/" + R.raw.sample_video;
File inputFile = new File(uri);
try {
InputStream is = new FileInputStream(inputFile);
byte[] bytes = new byte[50];
is.read(bytes);
Log.d("test", new String(bytes));
} catch(IOException e) {
}
The new FileInputStream line throws a FileNotFoundException regardless of what variation i try on the URI, but every piece of evidence I see seems to agree that this is the correct form.
For reasons relating to the architecture of the project, the Resource methods that return an InputStream directly aren't an option here, so the URI is the only option that I can see.
What is going wrong? Am I mistaken in how to specify the URI for this file? Is this test code not representative of whether or not the VideoView will be able to read the file? If not, what is? Does this test code work for you (which would indicate that something must be wrong with my project configuration)?

To get the URI of sample_video in raw folder :
Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.sample_video); //do not add any extension
To play the video :
videocontainer.setVideoURI(Uri.parse(videoUri));
videocontainer.start();
where videocontainer of type videoview.

Related

Cannot be resolved to absolute file path because it does not reside in the file system

My Code:
XWPFDocument doc = new XWPFDocument(OPCPackage.open(ResourceUtils.getFile("classpath:assets/OPTIONS_" + jubilar1.getJubiLanguage().toUpperCase() + ".docx")));
I have already tried instead of .getFile(), extractJarFileFromURL or resource.getInputStream() but all this does not work. When I package my project and run it as a jar file and it tries to open the following file it always returns the following message.
Error:
java.io.FileNotFoundException: class path resource [assets/OPTIONS_DE.
docx] cannot be resolved to absolute file path because it does not
reside in the file system:
jar:file:/home/tkf6y/IdeaProjects/hrapps/backend/target/backend-3.0.0.jar!/BOOT-INF/classes!/assets/OPTIONS_EN.docx
So yes it was the problem, as you are now using an InputStream as I suggested. The problem was (and always has been) the getFile stuff. What I suggest to do is don't use what you have now but rather do a new ClassPathResource(your location).getInputStream()) instead, it is easier, or even use a ResourceLoader (a Spring interface you can inject) and then use the path you had an again use getInputStream(). –
This works for me.
String strJson = null;
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}

createNewFile - open failed: ENOENT (No such file or directory)

I can't figure out what's going wrong here...I've tried writing this more succicinctly, that didn't work. I put in all the extra strings after reading other suggestions with this problem. Not helping. No clue what's happening. Could it be permissions-related? AFAIK I'm trying to write to internal memory and that doesn't need special permissions?
public void outputBitmap(){
String path = Environment.DIRECTORY_PICTURES.toString();
File folder = new File(path + "/Blabla");
String filename = new SimpleDateFormat("yyMMddHHmmss").format(Calendar.getInstance().getTime()) + ".png";
try {
if (!folder.exists()) {
folder.mkdirs();
System.out.println("Making dirs");
}
File myFile = new File(folder.getAbsolutePath(), filename);
myFile.createNewFile();
FileOutputStream out = new FileOutputStream(myFile);
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
It goes "Making dirs" every time, the directory is not staying made, or something. When it gets to myFile.createNewFile(); it gives the error message "open failed: ENOENT (No such file or directory)"
Not sure if it's related, but the information I am trying to output is from:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
myBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.RGB_565);
Canvas pngCanvas = new Canvas(myBitmap);
...[some maths and stuff]
canvas.drawLine(...);
pngCanvas.drawLine(...);
}
I thought I should be able to use the same canvas for the bitmap, but that caused crashed, so I'm writing the same information to both canvases. So...I don't know if that's related to the issue or a totally different bad issue or what.
Been searching all kinds of questions that seemed similar, but couldn't find any solutions that worked for me. I've been trying to solve this for days now. Anyone know what's going wrong?
Thanks
You are not using Environment.DIRECTORY_PICTURES correctly. It is not a folder by itself, you need to use it as a parameter to getExternalStoragePublicDirectory() method.
Check here : http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)
Possible Issue:
Make sure you have given following required permission in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And for Marhsmallow devices, make sure Contacts Groups Permissions is granted too by device user.
Ref: http://developer.android.com/training/permissions/requesting.html
Just change the begining of your code from this:
public void outputBitmap(){
String path = Environment.DIRECTORY_PICTURES.toString();
File folder = new File(path + "/Blabla");
To this:
public void outputBitmap(){File folder = new File(getActivity().getExternalFilesDir(null) + IMAGE_DIRECTORY + "whatever you want for your directory name");

Android - content provider file not found exception

I've a little content provider to open a simple pdf in my app package with an external application, but whe the open() run the parcelfiledescription return me a FileNotFoundException.
I don't understand what is the right sintax to give the correct file path to the parcel descriptor...
public ParcelFileDescriptor openFile(Uri uri, String mode) {
Log.i("info","eseguo providing");
URI uri1 = URI.create("file:///data/data/package.name/assets/prova.pdf");
File file = new File(uri1);
ParcelFileDescriptor parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
return parcel;
}
Thanks for any help!
i've tried this simple code:
URI uri1 = URI.create("file:///android_asset/prova.pdf");
File file = new File(uri1);
Log.i("info","file exist: " + file.exists());
but it return ever false!
From [ParcelFileDescriptor.open method][1] (bold emphasis mine)
FileNotFoundException Throws FileNotFoundException if the given file does not exist or can not be opened with the requested mode.
Have you tried changing the MODE to MODE_READ_ONLY and see if that works?
[1]: http://developer.android.com/reference/android/os/ParcelFileDescriptor.html#open(java.io.File, int)

URI scheme is not "file"

I get the exception: "URI scheme is not file"
What I am doing is trying to get the name of a file and then save that file (from another server) onto my computer/server from within a servlet.
I have a String called "url", from thereon here is my code:
url = Streams.asString(stream); //gets the URL from a form on a webpage
System.out.println("This is the URL: "+url);
URI fileUri = new URI(url);
File fileFromUri = new File(fileUri);
onlyFile = fileFromUri.getName();
URL fileUrl = new URL(url);
InputStream imageStream = fileUrl.openStream();
String fileLoc2 = getServletContext().getRealPath("pics/"+onlyFile);
File newFolder = new File(getServletContext().getRealPath("pics"));
if(!newFolder.exists()){
newFolder.mkdir();
}
IOUtils.copy(imageStream, new FileOutputStream("pics/"+onlyFile));
}
The line causing the error is this one:
File fileFromUri = new File(fileUri);
I have added the rest of the code so you can see what I am trying to do.
The URI "scheme" is the thing that comes before the ":", for example "http" in "http://stackoverflow.com".
The error message is telling you that new File(fileUri) works only on "file:" URI's (ones referring to a pathname on the current system), not other schemes like "http".
Basically, the "file:" URI is another way of specifying a pathname to the File class. It is not a magic way of telling File to use http to fetch a file from the web.
Your assumption to create File from URL is wrong here.
You just don't need to create a File from URL to the file in the Internet, so that you get the file name.
You can simply do this with parsing the URL like that:
URL fileUri = new URL("http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/domefisheye/ladybug/fish4.jpg");
int startIndex = fileUri.toString().lastIndexOf('/');
String fileName = fileUri.toString().substring(startIndex + 1);
System.out.println(fileName);

Given a classpath resource, is there a way to get the java.io.File object that has/contains it?

If I have a resource on a classpath, I can both load it as stream fine, and there is even a URL representation of it. Unfortunately some implementations of the Url do not implement lastModified correctly.
What I would like is to take a path to something in the classpath, and then resolve it to a file that it is in on disk - if it in a jar, then a File pointing to the jar is fine. I can then get the lastModified from the File object instead of the URL, which will be more helpful.
Roughly speaking:
URL url = this.getClass().getResource(myResource);
String fileName;
if (url.getProtocol().equals("file")) {
fileName = url.getFile();
} else if (url.getProtocol().equals("jar")) {
JarURLConnection jarUrl = (JarURLConnection) url.openConnection();
fileName = jarUrl.getJarFile().getName();
} else {
throw new IllegalArgumentException("Not a file");
}
File file = new File(fileName);
long lastModified = file.lastModified();
Should do what you want. You will need to catch IOException.
No. This can't be done generally because URL can represent resources which are not associated with a file. For example, it can be HTTP, FTP or JNDI etc.
You can check for protocol and create the File yourself if the protocol is file-based, like "file://path", "jar://path!...".

Categories