在Java中,可以使用java.net.URL
类来下载文件。下面是一个简单的示例代码:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class FileDownloader {
public static void downloadFile(String fileUrl, String savePath) throws IOException {
URL url = new URL(fileUrl);
BufferedInputStream inputStream = new BufferedInputStream(url.openStream());
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
public static void main(String[] args) {
String fileUrl = "https://example.com/file.txt";
String savePath = "/path/to/save/file.txt";
try {
downloadFile(fileUrl, savePath);
System.out.println("文件下载完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的示例代码中,downloadFile
方法接受文件的URL和保存的路径作为参数,通过URL
类打开输入流并使用BufferedInputStream
进行缓冲读取,然后使用FileOutputStream
写入到指定的文件中。最后,关闭输入流和输出流。
在main
方法中,你可以替换fileUrl
和savePath
为你要下载的文件的URL和保存的路径。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/854368.html