How to target a file (a path to it) in Java/JavaFX

雨燕双飞 提交于 2019-11-26 21:26:27

问题


It might be a simple one, but i can't seem to get it to work. I am making a video player in JavaFX but I don't know how to target the file that is going to be played (I don't know the correct syntax). Thank you in advance for your help. Here's a sample of code that i'm trying to run>

    Media media = new Media("trailers/trailer.mp4");
    MediaPlayer player = new MediaPlayer(media);
    MediaView view = new MediaView(player);

btw, the file is in the project folder, then trailers/trailer.mp4. Oh, and I'm running Windows.


回答1:


Put your file into the sources folder and load it as a resource:

Media media = new Media(getClass().getResource("trailer.mp4"));

or use the full path

Media media = new Media("file://c:/trailers/trailer.mp4"));

Also, note that JavaFX 2.0 supports only FLV codec. For mp4 (with H.264 codec) you need to use JavaFX 2.1 or later.




回答2:


1 Use this if media source file in same project package.

 Media media = new Media("trailer.mp4");

2 Use this if media source file in same project sub package [Packages with name "trailers" in project main package]

 Media media = new Media("trailers/trailer.mp4");

3 Use this if media source file is other location [Using full path].

 Media media = new Media("file:///e:/trailers/trailer.mp4");

OR

 Media media = new Media("file:///E:/trailers/trailer.mp4");

Note: should use 3 slash i.e. "file:///" to avoid error "MediaException: MEDIA_INACCESSIBLE : e/E"




回答3:


If you want to load media from your project package:

File file=new File("trailer.mp4");
Media media=new Media(file.toURI().toString())


来源:https://stackoverflow.com/questions/10062270/how-to-target-a-file-a-path-to-it-in-java-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!