📅  最后修改于: 2023-12-03 14:42:17.483000             🧑  作者: Mango
在 Java 中,我们可以使用 java.net.URL
和 java.net.HttpURLConnection
类来进行文件下载操作。
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void download(String urlStr, String file) throws Exception {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
}
public static void main(String[] args) {
String urlStr = "https://example.com/some-file.txt";
String file = "some-file.txt";
try {
download(urlStr, file);
System.out.println("File Downloaded Successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码中,download()
方法接收一个 URL 字符串和一个文件名字符串,通过 java.net.URL
类打开一个连接,然后获取输入流和输出流进行文件下载操作。如果下载成功,控制台将输出 "File Downloaded Successfully!"。
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloader {
public static void download(String urlStr, String file) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.close();
inputStream.close();
}
public static void main(String[] args) {
String urlStr = "https://example.com/some-file.txt";
String file = "some-file.txt";
try {
download(urlStr, file);
System.out.println("File Downloaded Successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
与方法一相比,方法二使用的是 java.net.HttpURLConnection
类。这种方式更加灵活,可以方便地设置请求头等参数。
以上就是使用 Java 下载文件的两种方法了。如果您有更好的方法,欢迎在评论区分享。