在Java中,可以使用URLConnection类来下载文件。以下是一个简单的示例代码:
import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class FileDownloader { public static void downloadFile(String url, String outputFile) { try { URL fileUrl = new URL(url); URLConnection connection = fileUrl.openConnection(); InputStream inputStream = connection.getInputStream(); FileOutputStream outputStream = new FileOutputStream(outputFile); 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 (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { downloadFile("http://example.com/file.jpg", "file.jpg"); } }
在上面的示例中,downloadFile
方法接受要下载的文件的URL和要保存到的本地文件的路径作为参数。它使用URLConnection类来打开URL连接并获取输入流,然后使用FileOutputStream类来保存文件内容到本地文件。最后,关闭输入流和输出流并输出下载成功的消息。您可以将要下载的文件的URL和要保存到的本地文件的路径替换为您自己的值。