[英]How to use this.getClass().getResource(String)?
I cant understand what the error of this code. 我无法理解这段代码的错误。
public void run(String url) {
try {
FileInputStream file;
file = new FileInputStream(this.getClass().getResource(url));
Player p = new Player(file);
p.play();
}catch(Exception e){
System.err.print( url + e);
}
}
when i try to run it, it says me "no suitable constructor found for FileInputStream(URL)". 当我尝试运行它时,它说我“没有为FileInputStream(URL)找到合适的构造函数”。 Why its happening?
为什么会这样?
Use: 采用:
getClass().getResourceAsStream(classpathRelativeFile)
for classpath resources getClass().getResourceAsStream(classpathRelativeFile)
路径资源的getClass().getResourceAsStream(classpathRelativeFile)
new FileInputStream(pathtoFile)
for file-system resources. new FileInputStream(pathtoFile)
。 It is simpler to use getResourceAsStream 使用getResourceAsStream更简单
InputStream in = getClass().getResourceAsStream(url);
Player p = new Player(file);
Put the file in root of folder of your class path (folder where your .class
files are generated) and then use statements below: 将文件放在类路径的文件夹的根目录(生成
.class
文件的文件夹)中,然后使用以下语句:
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream(filePath);
Player p = new Player(inputStream );
Here filePath
is the relative file path wrt the root folder. 这里
filePath
是根文件夹的相对文件路径。
The parameter of FileInputStream constructor is File, String ... (see http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html ), but Class.getResource return URL (see http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html ), not File, or String. FileInputStream构造函数的参数是File,String ...(请参阅http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html ),但Class.getResource返回URL(请参阅http ://docs.oracle.com/javase/6/docs/api/java/lang/Class.html ),而不是File或String。 Try to use
尝试使用
public void run(String url) {
try {
FileInputStream file;
file = new FileInputStream(new File(this.getClass().getResource(url).toURI()));
Player p = new Player(file);
p.play();
}catch(Exception e){
System.err.print( url + e);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.