gpt4 book ai didi

java - 在 Java 代码中定位文件

转载 作者:行者123 更新时间:2023-12-01 17:25:46 27 4
gpt4 key购买 nike

我正在尝试制作一个播放声音的简单应用程序。我的 java 项目中有一个名为 sound.wav 的声音文件(使用 eclipse 顺便说一句)。我不确定如何导航到声音文件。问题是我不知道如何通过代码导航到声音文件。我现在运行的程序抛出空指针异常,即。该文件不存在。这是到目前为止我的代码:

    private static Sound sound;

public static void main(String[] args) {
JFrame j = new JFrame("Sound");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setSize(300, 150);
sound = new Sound("/Users/Chris/Desktop/Workspace/Sound/sound.wav");
//this is the problem line
JButton play = new JButton("Play");
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sound.play();
}

});

j.add(play,BorderLayout.SOUTH);
j.setVisible(true);
}

这是我的声音类的代码:

    private AudioClip clip;

public Sound(String fileName) {
try {
clip = Applet.newAudioClip(Sound.class.getResource(fileName));
}
catch (Exception e) {
e.printStackTrace();
}
}

public void play() {
try {
new Thread(){
public void run() {
clip.play();
}
}.start();
}
catch (Exception e) {
e.printStackTrace();
}
}

最佳答案

Class.getResource(),正如其 javadoc 所示,从类路径读取资源。不是来自文件系统。

如果您想从文件中读取数据,则应使用文件 IO(即 FileInputStream),或者您想从类路径中读取数据,则应使用 Class.getResource( ) 并传递一个资源路径,从类路径的根开始。例如,如果 sound.wav 位于运行时类路径中,在包 com.foo.bar.sounds 中,则代码应为

Sound.class.getResource("/com/foo/bar/sounds/sound.wav")

关于java - 在 Java 代码中定位文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15042762/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com