Application of JavaIO Streaming and Network Programming

Application of JavaIO Streaming and Network Programming

principle

Java programs can access the Internet through URLs, and browsers or other programs can search for corresponding resources on the Internet after using a given URL.
Step 1: Construct the URL object
Step 2: Obtain the resource pointed to
by the URL. Read one or more resources specified by the URL through the openStream() method. Step 3: Set
up a connection and return to InputStream to read the data in the resource. Up.

Code

Show some below 内联代码片.

public static void main(String[] args) throws Exception {
    
    
		// 构造URL对象并获取资源路径
		URL url1 = new URL("http://www.shijuepi.com/uploads/allimg/200918/1-20091Q10420.jpg");
		URL url2 = new URL("http://img.ewebweb.com/uploads/20191006/20/1570365161-shmEFlWfHU.jpg");
		URL url3 = new URL("http://www.shijuepi.com/uploads/allimg/200918/1-20091Q10421.jpg");
		URL url4 = new URL("https://www.diyifanwen.com/images/sichuan/0872403401922790.jpg");
		URL url5 = new URL("http://img10.3lian.com/sc6/show02/33/27/332702.jpg");
		URL url6 = new URL("http://www.scdongqu.gov.cn/uploadfiles/201812/17/2018121711091024292013.jpg");
		// 创建一个数组
		ArrayList<URL> arrayList = new ArrayList<URL>();
		// 添加元素
		arrayList.add(url1);
		arrayList.add(url2);
		arrayList.add(url3);
		arrayList.add(url4);
		arrayList.add(url5);
		arrayList.add(url6);
		for (int i = 0; i < arrayList.size(); i++) {
    
    
			// 通过openStream()方法读取一个或多个URL所指定的资源
			InputStream openStream = arrayList.get(i).openStream();
			// 在磁盘中给定指定的路径用于存放资源
			File file = new File("E:" + File.separator + "IP" + File.separator + i + ".jpg");
			// 通过建立连接并返回InputStream,可以读取资源中的数据了
			FileOutputStream fileOutput = new FileOutputStream(file);
			int len = 0;
			while ((len = openStream.read()) != -1) {
    
    
				fileOutput.write(len);
			}
			// 最后关闭流
			openStream.close();
			fileOutput.flush();
			fileOutput.close();
		}

	}

Achievement display

Insert picture description here

Note and summary

When you have only one resource, it is relatively simple to remove the collection. When using a collection to read a large number of network resources, pay attention to using traversal to read each resource into a specified folder. The file storage location here is a folder manually created on the disk by yourself. Friends should pay attention to this when writing by themselves, otherwise the system will have a bug that denies access.

Guess you like

Origin blog.csdn.net/fdbshsshg/article/details/114294076