Error in passing file location in Java [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm trying to create a media Player in Java.
In order to do that, I'm passing a string where my file is located but I am getting an error.
Operating System: MacOSX
IDE: Pycharm
#Override
public void start(Stage primaryStage) throws Exception{
String file="~/Users/ViditShah/IdeaProjects/MediaPlayer/src/sample/1.mp4";
Player player = new Player(file);
Scene scene = new Scene(player,720,480, Color.BLACK);
primaryStage.setScene(scene);
primaryStage.show();
}
Player Class:
public class Player extends BorderPane {
Media media;
MediaPlayer player;
MediaView view;
Pane apane;
Player(String file)
{
media =new Media(file);
player = new MediaPlayer(media);
view = new MediaView(player);
apane.getChildren().add(view);
setCenter(apane);
}
}
The error is being shown in parsing the file String.
I guess I have made a mistake in locating my file path and failing to find solution.

You are apparently trying to pass a filesystem path to the Media constructor. According to the documentation:
The Media class represents a media resource. It is instantiated from the string form of a source URI.
and
The source must represent a valid URI and is immutable. Only HTTP, FILE, and JAR URLs are supported. If the provided URL is invalid then an exception will be thrown.
So it makes no sense at all to pass a filesystem path to the Media constructor. You have to pass it the string form of a URI.
There are two different scenarios that are possible here (and for some reason, you refuse to clarify which you are trying to do). Either you are trying to play a video which is part of your application, in which case the video will be included in the jar file for your application when it is deployed, or you are trying to play a video provided by the user at runtime.
In the former case, you basically need to load the video from wherever the JVM is loading classes (whether it be the file system, typically during development, or from a jar file, typically once the application is deployed). To do this, you get the URI from the class loader.
If the video is in the same package as the current class, you can do:
String videoURI = getClass().getResource("1.mp4").toURI().toString();
and pass that (via your Player constructor) to the Media constructor.
Or more generally, you can start the resource name with a /, in which case it will be searched relative to the classpath:
String videoURI = getClass().getResource("/sample/1.mp4").toURI().toString();
On the other hand, if you are playing a video that the user provides, you can create a URI from a File object:
File file = ... ;
String videoURI = file.toURI().toString();
For example, you might do:
FileChooser chooser = new FileChooser();
chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("mp4 video files", "*.mp4"));
File file = chooser.showOpenDialog(primaryStage);
if (file != null) {
String videoURI = file.toURI().toString();
// ...
}

Related

How to have my java project to use some files without using their absolute path?

I have written a project where some images are used for the application's appearance and some text files will get created and deleted along the process. I only used the absolute path of all used files in order to see how the project would work, and now that it is finished I want to send it to someone else. so what I'm asking for is that how I can link those files to the project so that the other person doesn't have to set those absolute paths relative to their computer. something like, turning the final jar file with necessary files into a zip file and then that the person extracts the zip file and imports jar file, when runs it, the program work without any problems.
by the way, I add the images using ImageIcon class.
I'm using eclipse.
For files that you just want to read, such as images used in your app's icons:
Ship them the same way you ship your class files: In your jar or jmod file.
Use YourClassName.class.getResource or .getResourceAsStream to read these. They are not files, any APIs that need a File object can't work. Don't use those APIs (they are bad) - good APIs take a URI, URL, or InputStream, which works fine with this.
Example:
package com.foo;
public class MyMainApp {
public void example() {
Image image = new Image(MyMainApp.class.getResource("img/send.png");
}
public void example2() throws IOException {
try (var raw = MyMainApp.class.getResourceAsStream("/data/countries.txt")) {
BufferedReader in = new BufferedReader(
new InputStreamReader(raw, StandardCharsets.UTF_8));
for (String line = in.readLine(); line != null; line = in.readLine()) {
// do something with each country
}
}
}
}
This class file will end up in your jar as /com/foo/MyMainApp.class. That same jar file should also contain /com/foo/img/send.png and /data/countries.txt. (Note how starting the string argument you pass to getResource(AsStream) can start with a slash or not, which controls whether it's relative to the location of the class or to the root of the jar. Your choice as to what you find nicer).
For files that your app will create / update:
This shouldn't be anywhere near where your jar file is. That's late 80s/silly windows thinking. Applications are (or should be!) in places that you that that app cannot write to. In general the installation directory of an application is a read-only affair, and most certainly should not be containing a user's documents. These should be in the 'user home' or possibly in e.g. `My Documents'.
Example:
public void save() throws IOException {
Path p = Paths.get(System.getProperty("user.home"), "navids-app.save");
// save to that file.
}

(Processing) Converting type file into type string?

I'm trying to get my application to open an audio file via a button (which works) and display the data of the file in the console (which also works)
The application is unable to play the file because the function needs a type String and the audio file I'm using is of type File. How do you convert a File into a String in Processing?
void setup() {
selectFile();
size(300, 300);
}
void selectFile() {
selectInput("Select a file to process:", "fileSelected");
}
void songTag(File selection) {
File file = new File(selection.getPath());
song = minim.loadFile(filepath);
song.play();
}
}
}
Check out the Java API to understand Java classes and functions.
The File class has several useful functions. You probably want the getAbsolutePath() function.
I'm not sure which line of code is showing the compiler error, but you might try something like this:
Mp3File mp3file = new Mp3File(selection.getAbsolutePath());
song = minim.loadFile(selection.getAsbolutePath());
Also note that the code you posted has other errors: the filepath function is never defined, for example. In the future, please try to post a MCVE that actually shows exactly what you're trying to do.

Java: Referencing a file after being packaged (jar), getResourceAsStream? [duplicate]

This question already has an answer here:
Any way to get a File object from a JAR
(1 answer)
Closed 5 years ago.
I'm trying to implement a button into my project which, when clicked, automatically loads a specific file. Currently there are buttons for users selecting a file from their hard disk.
So, I downloaded the specific file and inserted it into the project. When using File f = new File("demofile") or something like this
getClass().getResource("/resources/file.txt").getFile(); the code WORKS locally.
However, when the project is packaged, a FileNotFoundException is thrown.
After much research online, there are suggestions to use something like:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
However, for this project, I need the file to be referenced as a file object so that it can be passed as an argument to other functions, such as:
in = new TextFileFeaturedSequenceReader(TextFileFeaturedSequenceReader.FASTA_FORMAT, file, DiffEditFeaturedSequence.class);
Any ideas on how I can solve this, or read a stream into a file object?
Thanks!
If you absolutely must pass a File, copy your resource to a temporary file:
Path path = Files.createTempFile(null, null);
try (InputStream stream =
getClass().getResourceAsStream("/resources/file.txt")) {
Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
}
in = new TextFileFeaturedSequenceReader(
TextFileFeaturedSequenceReader.FASTA_FORMAT,
path.toFile(),
DiffEditFeaturedSequence.class);
// Use the TextFileFeaturedSequenceReader as needed
// ...
Files.delete(path);

Slash character in file path creating exception in javafx media

I found many similar questions on this topic in this forum, but none of the solutions of those questions working for me and this problem is really making me frustrated.
I have the following method which should play a wav file when I call it.
Directory of the wav file is: ProjectFolder/src/resources/Sounds/click.wav
public static void Click()
{
String clickSound = "/resources/Sounds/click.wav";
Media hit = new Media(new File(clickSound).toPath().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}
But it results in the following exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: java.net.URISyntaxException: Illegal character in path at index 0: \resources\Sounds\click.wav
at javafx.scene.media.Media.<init>(Media.java:385)
When I set the value of the string clickSound "resources/Sounds/click.wav" instead of "/resources/Sounds/click.wav", the exception says illegal character in path at index 9.
So I am guessing that it is considering '/' character as an illegal character. I tried using '\' instead of '/', but the result was same.
I do not want to change the location of the wav file for certain reason. How can access I access that wav file from ProjectFolder/src/resources/Sounds/click.wav and play it without any exception?
Any kind of help is appreciated.
Thanks in advance.
As stated in the documentation:
The source must represent a valid URI and is immutable. Only HTTP, HTTPS, FILE, and JAR URLs are supported. If the provided URL is invalid then an exception will be thrown.
You are passing in the path to a file, instead of a URI.
You almost certainly don't want a file here anyway; for example, when you deploy your application it will typically be deployed as a jar file, and the media will be an entry in that jar file (so it won't be a file in its own right at all). On top of that, the resources folder is typically part of the source code structure, and for obvious reasons the source code is not usually available at runtime.
Assuming your resources are being deployed to the root of the classpath, which is the usual setup, you need something like
String clickSound = "/Sounds/click.wav";
Media hit = new Media(getClass().getResource(clickSound).toExternalForm());
You listed the file as in directory "ProjectFolder/src/resource/Sounds/click.wav" but when trying to access you have "resources" instead of "resource"

Playing an mp3 file in BlueJ

I'm trying to play an mp3 file in BlueJ following this Stack question answer:
Playing .mp3 and .wav in Java?
I have the exact same code except the file name. Here is my code:
String bip = "Johnny.mp3";
Media hit = new Media(bip);
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
I CAN compile this, but when the program tries to run it I get an exception. Here is the entire error:
java.lang.IllegalArgumentException: uri.getScheme() == null! uri == 'Johnny.mp3'
at com.sun.media.jfxmedia.locator.Locator.<init>(Locator.java:211)
at javafx.scene.media.Media.<init>(Media.java:391)
at Game.goRoom(Game.java:282)
at Game.processCommand(Game.java:167)
at Game.play(Game.java:130)
Personally, I think this is related with the file path I have given. I know that the file exists in my project map but I'm very uncertain on the pathway they want, do they want a full pathway all the way from file:// or just the sound-files name which is what I have done? Note that this project doesn't have any resource folder like Eclipse projects have since this is how the IDE handles it files. The sound-file just lies in the same folder as all the classes so it's not sorted in any manner.
I have checked around, and it seems that if this is not my problem it would be that my JavaFX is not initialized. If this is the case, how would I go about it and how would the syntax look like?
Media takes your String value and tries to make a URI. Why the method doesn't just require you to pass it a URI (or URL) directly, I don't know.
The documentation outlines this rather well...
Constructs a Media instance. This is the only way to specify the media
source. The source must represent a valid URI and is immutable. Only
HTTP, FILE, and JAR URLs are supported. If the provided URL is invalid
then an exception will be thrown. If an asynchronous error occurs, the
error property will be set. Listen to this property to be notified of
any such errors.
...
Constraints:
The supplied URI must conform to RFC-2396 as required by java.net.URI.
Only HTTP, FILE, and JAR URIs are supported.
See java.net.URI for more information about URI formatting in
general. JAR URL syntax is specified in
java.net.JarURLConnection.
Parameters: source - The URI of the source media. Throws:
- java.lang.NullPointerException - if the URI string is null.
- java.lang.IllegalArgumentException - if the URI string does not
conform to RFC-2396 or, if appropriate, the Jar URL specification, or
is in a non-compliant form which cannot be modified to a compliant
form. - java.lang.IllegalArgumentException - if the URI string has a
null scheme. - java.lang.UnsupportedOperationException - if the
protocol specified for the source is not supported....
And if we have a look at the source, you can see it trying to wrap the String in a URI class...
public Media(#NamedArg("source") String source) {
this.source = source;
URI uri = null;
try {
// URI will throw NPE if source == null: do not catch it!
uri = new URI(source);
} catch(URISyntaxException use) {
throw new IllegalArgumentException(use);
}
So, depending on where the file is actually stored, you could use something like
Media hit = new Media(new File(bip).toURI().toURL().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
This also assumes that "Johnny.mp3" is in the current working directory of your program.
I say "depending" as you would use a different approach for media files which were located internally (bundled) with your application to those which are external.
In which case you might use something like...
Media hit = new Media(getClass().getResource(bip).toExternalForm());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
Here ya go:
MediaPlayer yourPlayer = new MediaPlayer(new Media(Paths.get("yourAudioFile").toUri().toString()));
Make sure to add the file extension onto the audio file! Also, import the following:
import java.nio.file.Paths;
I'm assuming you have the Media and MediaPlayer classes imported.

Categories

Resources