使用URL
目的URLConnection
によって、その後、接続を開く方法をInputStream
バイトストリームリーダーを取得
ファイル自体もバイトストリームであるため、別のファイルストリームライター、つまりOutputStream
ファイル名で作成されたオブジェクトを作成しInputStream
、コンテンツを書き込みOutputStream
ます。
ファイルのサフィックス名については、URLConnection
オブジェクトgetContentType
メソッドを通じてファイルタイプとサフィックス名を取得する必要があります。これは、名前を付けるのに便利です。
ファイルストリームが閉じた後に書き込みが発生することに注意してください。閉じることを忘れないでくださいOutputStream
import java.util.*;
import java.net.*;
import java.io.*;
public class Downloader {
URL url;
public void setURL(String u) throws Exception {
url = new URL(u);
}
Downloader(String u) throws Exception {
url = new URL(u);
}
Downloader() {
}
public void getResources(String savePath, String fileName) throws Exception {
// 建立连接对象
URLConnection con = url.openConnection();
con.connect();
// 获取并拆分资源的类别名
String type_tname = con.getContentType();
String[] t = type_tname.split("/");
String type=t[0], tname=t[1];
System.out.printf("获取了 .%s 类型文件\n\n", tname);
// 获取输入输出流
InputStream is = con.getInputStream();
FileOutputStream os = new FileOutputStream(savePath+fileName+"."+tname);
// 写入文件流,缓存为10MB
byte[] buf = new byte[10241024];
int len;
while((len=is.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.close();
}
public static void main(String[] args) throws Exception {
/*
https://www.baidu.com
https://www.baidu.com/img/bd_logo1.png
*/
String save_path = "E:/MyEclipse/WorkSpace/Hello/src/lab5/downloadfiles/";
String url, fileName;
Downloader dl = new Downloader();
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("请输入:url 保存的文件名");
url=scanner.next(); fileName=scanner.next();
dl.setURL(url);
dl.getResources(save_path, fileName);
}
}
}
ダウンロード成功!
HTMLおよびpngファイルは正常に開くことができます