温馨提示×

java下载文件到本地代码如何写

小亿
84
2024-04-01 15:47:57
栏目: 编程语言

以下是一个简单的Java代码示例,用于从指定的URL下载文件到本地:

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class FileDownloader {
    public static void main(String[] args) {
        String fileUrl = "https://example.com/sample.pdf";
        String saveDir = "C:/Downloads/";

        try {
            URL url = new URL(fileUrl);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();

            FileOutputStream out = new FileOutputStream(saveDir + "sample.pdf");
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            out.close();
            in.close();
            System.out.println("File downloaded successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我们首先指定要下载的文件的URL和要保存到的目录。然后,我们创建一个URL对象并打开与该URL的连接。通过获取输入流,我们读取文件的内容,并通过输出流将其写入本地文件。最后,我们关闭输入输出流,并打印成功下载的消息。请注意,这只是一个简单的示例,实际应用中可能需要处理更多的异常情况和增加错误处理。

0