如何使用Java在线下载mp3文件?

bluesky3月前 ⋅ 28 阅读

ChatGPT的回答仅作参考:

您可以使用Java的URLConnection类来下载mp3文件。以下是一个示例代码:

```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class Mp3Downloader {
    public static void main(String[] args) {
        String mp3Url = "http://example.com/example.mp3";
        String savePath = "C:/example.mp3";

        try {
            URL url = new URL(mp3Url);
            URLConnection conn = url.openConnection();
            conn.connect();

            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            FileOutputStream fos = new FileOutputStream(savePath);

            byte[] buffer = new byte[1024];
            int count;
            while ((count = bis.read(buffer, 0, 1024)) != -1) {
                fos.write(buffer, 0, count);
            }

            fos.close();
            bis.close();
            System.out.println("Download completed.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

在上面的代码中,您需要将mp3Url替换为要下载的mp3文件的URL,将savePath替换为要保存文件的路径。运行该代码将下载mp3文件并将其保存到指定路径。

全部评论: 0

    相关推荐