在Java中,可以使用URLConnection
类来下载文件到本地。以下是一个简单的示例代码:
import java.io.*; import java.net.URL; import java.net.URLConnection; public class FileDownloader { public static void main(String[] args) { String fileUrl = "http://example.com/sample.jpg"; String saveDir = "C:/Downloads/"; try { URL url = new URL(fileUrl); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); FileOutputStream outputStream = new FileOutputStream(saveDir + fileName); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("File downloaded successfully!"); } catch (IOException e) { e.printStackTrace(); } } }
在上面的代码中,我们首先指定了要下载的文件的URL和保存目录,然后创建一个URL对象并打开连接。接下来,我们获取输入流并创建一个输出流,将下载的文件写入到本地。最后关闭输入流和输出流,下载完成。
请注意,上述示例中的URL和保存目录是示例值,您需要根据实际情况修改为您要下载的文件的URL和保存目录。