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 に変換しようとしています。BAD IDEA.™</p>

を呼び出すとmp3Files[i].getFile()、URL 全体ではなく、ファイル名部分のみが取得されます。URL オブジェクトを渡すだけです。saveFile(MP3Engine.MP3_LOCATION + "sound" + i + ".mp3", mp3Files[i]);

于 2013-09-19T16:06:18.123 に答える