在Java中可以通过使用URLConnection类来实现文件下载功能。以下是一个简单的示例代码:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownload {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.zip";
String outputFilePath = "file.zip";
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(outputFilePath);
byte[] buffer = new byte[4096];
int bytesRead = -1;
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();
}
}
}
在这个示例中,我们首先创建一个URL对象,然后通过调用openConnection()方法获取URLConnection对象。接着我们获取输入流并将其写入到一个文件输出流中,最后关闭输入输出流。这样就实现了文件下载功能。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/979389.html