java.net.MalformedURLException:无协议:下载mp3文件时出错

时间:2013-09-19 15:42:54

标签: java url mp3

每当我启动程序时,我都会在控制台中看到它:

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中使用文件下载,所以任何帮助都表示赞赏:)

1 个答案:

答案 0 :(得分:0)

您正在尝试将URL转换为要传递的字符串以保存文件,然后将其转换回URL。 BAD IDEA。™

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