0

每当我启动我的程序时,我都会在我的控制台中得到这个:

java.net.MalformedURLException: no protocol: /test.mp3

代码:

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MP3Fetcher implements Runnable {
    public URL[] mp3Files = new URL[100];
    public void load() {
        (new Thread(new MP3Fetcher())).start();
    }

    public void getMp3Files() throws MalformedURLException {
        mp3Files[0] = new URL("http://regicide.ucoz.com/test.mp3");
        mp3Files[1] = new URL("http://regicide.ucoz.com/test2.mp3");
    }

    public void fetchMp3Files() throws MalformedURLException, IOException {
        for (int i = 0; i < mp3Files.length; i++) {
            if (mp3Files[i] != null) {
                if (!mp3Exists(i)) {
                    saveFile(MP3Engine.MP3_LOCATION + "sound" + i + ".mp3",
                            mp3Files[i].getFile());
                }
            }
        }
    }

    public static boolean mp3Exists (int id) {
        File mp3 = new File(MP3Engine.MP3_LOCATION + "sound" + id + ".mp3");
        return mp3.exists();
    }

    public void saveFile(String filename, String urlString) throws MalformedURLException, IOException {
        URL url;
        URLConnection con;
        DataInputStream dis;
        FileOutputStream fos;
        byte[] fileData;
        try {
            url = new URL(urlString); // File Location goes here
            con = url.openConnection(); // open the url connection.
            dis = new DataInputStream(con.getInputStream());
            fileData = new byte[con.getContentLength()];
            for (int q = 0; q < fileData.length; q++) {
                fileData[q] = dis.readByte();
            }
            dis.close(); // close the data input stream
            fos = new FileOutputStream(new File(
                    filename)); // FILE Save
                                                                  // Location
                                                                  // goes here
            fos.write(fileData); // write out the file we want to save.
            fos.close(); // close the output stream writer
        } catch (Exception m) {
            System.out.println(m);
        }
    }

    public void run() {
        try {
            getMp3Files();
            fetchMp3Files();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我能做些什么来解决这个问题?

我尝试将 file:// 添加到我的文件路径,但没有奏效。这是我第一次在 Java 中使用文件下载。

4

1 回答 1

0

您正在尝试将 URL 转换为字符串以传递给保存文件,然后将其转换回 URL。坏主意。™</p>

通过调用mp3Files[i].getFile(),您只会获得文件名部分而不是整个 URL。只需传递 URL 对象。saveFile(MP3Engine.MP3_LOCATION + "sound" + i + ".mp3", mp3Files[i]);

于 2013-09-19T16:06:18.123 回答