When I embed my resource and use the follwoing:
getClass().getResourceAsStream("sound.wav")
I get the following:
could not get audio input stream from input stream
If I link directly to the file it works fine.
If I link directly to the file it works fine.
It seems that you mean File or URL by that. (Can you confirm that & which one you mean, if so?) In that case, you'll often find that Java Sound requires a repositionable InputStream, which is (strangely) not what getResourceAsStream() returns.
The solution to that problem is to load the sound from URL. Obtain the URL using something like:
URL urlToClip = this.getClass().getResource("sound.wav");
// sanity check!
System.out.println("urlToClip: " + urlToClip);
Related
I want to be able to play audio files from my Java based web application
Now its possible if the file physically sits in a folder below the root folder of my web application
<audio controls="controls">
<source src="/musicserver/test.mp3">
</audio>
but not if it is somewhere else on the machine, I got round this using a symbolic link but this caused another issue that means I cannot use this approach.
So another solution suggested was to instead call a playmusic endpoint passing it the file path as a parameter. like this.
<audio controls="controls">
<source src="/musicserver/playmusic?url=/musicfolder/test.mp3">
</audio>
But I dont know what this endpoint should actually do. The server is written in Java and I can read the file okay, but what should it actually return to allow audio controls to play the music.
First set the response mime type to audio/mpeg, read the mp3 file as raw bytes, basically any servlet response beside xml/json/html you want to write byte[] to response stream.
res.setContentType("audio/mpeg");
//this whole block should be in a try catch
FileInputStream fis = new FileInputStream(new File("yourmp3file.mp3"));
int c;
while((c=fis.read())!=-1){
res.getWriter().write(c);
}
res.getWriter().flush();
I have a little problem with Struts 2 when I try to get the context path :
ServletActionContext.getServletContext().getRealPath("\\WebContent\\resources\\img\\");
I got this path:
C:\Users\killian\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SiteWebAdministrable\WebContent\resources\imgicone.jpg
Why the exact source path ?
Because i need to upload and save images for an admin website to control background and without the actual path i cannot save images in the resources path...
So i save the path with the name and extension in the database (no problem), and i need to save the image in the resource directory (image problem...)
Can someone help me please ? Did i forgot something ?
This question is the answer ?
How do you get the project path in Struts 2?
servletContext.getServletContext().getRealPath("/resources/img/name_of_image.png")
So, passing the "/" to getRealPath() would return you the absolute disk file system path of the /web folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/demo.war/ which you should be able to further use in File or FileInputStream.
Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use
String absolutePathToIndexJSP = servletContext.getRealPath("/") + "demo.png";
instead of
String absolutePathToIndexJSP = servletContext.getRealPath("/demo.png");
getRealPath() is unportable; you'd better never use it
Use getRealPath() carefully.
If all you actually need is to get an InputStream of the web resource, better use ServletContext#getResourceAsStream() instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream of index.jsp, then do not do:
InputStream input = new FileInputStream(servletContext.getRealPath("/demo.png")); // Wrong!
But instead do:
InputStream input = servletContext.getResourceAsStream("/demo.png"); // Right!
Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.
Set<String> resourcePaths = servletContext.getResourcePaths("/");
I have an Android application that i'm working on and now i'm trying to get a File from an URI (i'll use an intent to get an image from gallery and then upload it to a node.js server using Ion). Te problem is it always throws an exception. I tried debugging and got the Uri.toString(). It looks something kind of like this:
content://com.android.providers.media.documents/document/image%3A102
I know for a fact that it should look like this:
content://com.android.providers.media.documents/document/image:102
I know that the %3A is a representation of :, but why does it appear in the Uri and, how can i fix it? Finally, how can i get my file from this Uri?
i'm trying to get a File from an URI
A Uri is not a file. A Uri does not have to point to anything on the filesystem, let alone a place that you can access.
but why does it appear in the Uri
A Uri is an opaque handle. It can be whatever the ContentProvider wants it to be.
how can i fix it?
You don't, any more than you "fix" https://stackoverflow.com/questions/41795342/get-path-from-uri-throws-exception because you do not like eight-digit numbers starting with 4. Just as the Stack Overflow Web server defines that URLs it uses, so does a ContentProvider define what Uri values it uses.
Finally, how can i get my file from this Uri?
Ideally, you don't. You use ContentResolver and openInputStream() to get an InputStream on the content identified by that Uri, and Ion uses that.
If Ion does not support this and can only work with a file, use the InputStream to copy the bytes to some FileOutputStream that you control (e.g., in getCacheDir()). Use that file for your upload, then delete the file when you are done.
I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.
The code I am using to load the image is:
ImageIO.read(SpriteSheet.class.getResource(path));
The path being the path to the resource. But it would error with IllegalArgumentException. I wondered what might be causing and came to the conclusion that the resource should be added into the same path as the class.
Is it possible to load the image from another folder, like a res folder outside of the bin folder? (folder holding compiled classes)
EDIT:
So i messed around with a few things, and came to a solution. But now I have another problem. Here is my code
File sheet = new File(SpriteSheet.class.getProtectionDomain().getCodeSource().getLocation().getPath());
URI uri = sheet.toURI();
BufferedImage image = ImageIO.read(uri.toURL());
When I try to run it, it gives me an IIOException: Can't read Input File
This means that I can never actually get it work. I tried debugging by prining the URL to the console and this is the URL.
C:\Users\Amma\Abhijeet\Eclipse%20Workspace1\Test%20Game\bin
The %20 comes in the middle. Meaning that the file is and never can be acceesed. Is there anyway I can fix this?
Thanks.
Class.getResource will return null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
All variants of ImageIO.read will throw an IllegalArgumentException if they receive a null input.
Take a look at the documentation of the getResource to understand how an absolute resource name is constructed from the given resource named and what are the rules for searching resources.
You can read images from any location as long as you have permissions to do so, the ImageIO.read method accepts a File, URL or InputStream so you have many option to do it.