简体   繁体   English

Java不会读取具有相对路径的图片和音频文件

[英]Java don't read in pictures and audio files with relative path

In java i programmed a small program to play audio file and sow pictures: 在Java中,我编写了一个小程序来播放音频文件和播种图片:
At first i make a final String with the path and then i made a file object. 首先,我使用路径创建了最终的String,然后创建了文件对象。
At least i save the returned array in my "tracks" variable. 至少我将返回的数组保存在“ tracks”变量中。 This is my code: 这是我的代码:

private static final String PATH = "../src/audio/";
private static final File FILE = new File(PATH);
tracks = liesAudioDateien(file);

private AudioClip[] liesAudioDateien (File inputFile) {
    File[] dateFileArray;
    AudioClip[] tracks;
    dateFileArray = inputFile.listFiles();
    tracks = new AudioClip[dateFileArray.length];
    for (int i = 0; i < tracks.length; i++) {
        if (dateFileArray[i].isFile()) {
            try {
                tracks[i] = Applet.newAudioClip(dateFileArray[i].toURL());
            } catch (IOException ex) {
                System.err.println("Oops!: -- " + ex.toString());
            }
        }

    }
    return tracks;   

If I run this code, I get an error: 如果运行此代码,则会出现错误:

Exception in thread "main" java.lang.NullPointerException
    at source.Sound.liesAudioDateien(Sound.java:32)

Sound.java:32: Sound.java:32:
This is tracks = new AudioClip[dateFileArray.length]; 这是tracks = new AudioClip[dateFileArray.length]; line. 线。

If i try with an absolute path, it does work! 如果我尝试使用绝对路径,它将起作用! What i do wrong? 我做错了什么?

Your path is relative, which is resolved to be relative to the current working directory. 您的路径是相对的,它被解析为相对于当前工作目录。 The current working directory is not what you think it is. 当前的工作目录不是您认为的那样。

Try to do this before inputFile.listFiles() ; 尝试在inputFile.listFiles()之前执行此inputFile.listFiles()

System.out.println(inputFile.getAbsolutePath());

And see what Java thinks the absolute path should be. 并查看Java 认为绝对路径应该是什么。

"../src/audio/"更改为"./src/audio/"

File.listFiles returns null if the abstract pathname does not denote a directory. 如果抽象路径名不表示目录,则File.listFiles返回null

You need to make sure inputFile does denote a directory to ensure dateFileArray is not null . 您需要确保inputFile 确实表示目录,以确保dateFileArray不为null

Try it with File.separator in place of forward/backward slash. 尝试使用File.separator代替正斜杠。 ex: 例如:

String soundDir = "." + File.separator + "folderName" + File.separator;
String fileName = "sound.wav";
String filePath = soundDir+ + fileName;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM