通过Url网络编程实现下载
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
//URL:統一資源定位符,一個URL的一個對象對應互聯網上的一個資源,
//通過URL的對象調用相應方法,將此資源讀取(“下載”)
public class TestUrl {
public static void main(String[] args) {
//穿件一個URL對象
try {
URL url = new URL("http://192.168.2.106:8080/exam/helloworld.txt");//File file = new File("文件路徑");
//讀取的方法
/**
* getProtocol 獲取URL的協議
* getHost 獲取URL主機名
* getPort 獲取URL端口號
* getPath 獲取URL文件路徑
* getFile 獲取URL文件名
* getRef 獲取URL在文件中的相對位置
* getQuery 獲取URL查詢名
*/
System.out.println("獲取URL的協議==>"+url.getProtocol());
System.out.println("獲取URL主機名==>"+url.getHost());
System.out.println("獲取URL端口號==>"+url.getPort());
System.out.println("獲取URL文件路徑==>"+url.getPath());
System.out.println("獲取URL文件名==>"+url.getFile());
System.out.println("獲取URL在文件中的相對位置==>"+url.getRef());
System.out.println("獲取URL查詢名==>"+url.getQuery());
//如何精服務器端的資源讀取出來openStream,該方法只負責度如數據
InputStream is = url.openStream();
byte[] b = new byte[20];
int len;
//輸出到控制臺
while((len = is.read(b)) != -1){
String str = new String(b,0,len);
System.out.println(str);
}
//如果有數據輸入,又有輸出,則考慮用URLConnection
//保存到本地文件
URLConnection urlConn = url.openConnection();
InputStream is1 = urlConn.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("abc.txt"));
byte[] b1 = new byte[20];
int len1;
while((len1 = is1.read(b1)) != -1){
fos.write(b1, 0, len1);
}
fos.close();
is1.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
轉載于:https://www.cnblogs.com/lixiuming521125/p/6428534.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的通过Url网络编程实现下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAva面试题(微信分享)
- 下一篇: distinct和group by的性能