有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

url java。网MalformedURLException:无协议:下载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中使用文件下载


共 (0) 个答案