java网络编程 之 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;

public class urlTest {

	public static void main(String[] args) {

		InputStream is = null;
		InputStream isConn = null;
		FileOutputStream fos = null;
		
		try {
			URL url = new URL("http://localhost:8080/examples/urlTestFile.txt?a=b");
			
			/*
			 *  public String getProtocol(  )     获取该URL的协议名
				public String getHost(  )           获取该URL的主机名
				public String getPort(  )            获取该URL的端口号
				public String getPath(  )           获取该URL的文件路径
				public String getFile(  )             获取该URL的文件名
				public String getRef(  )             获取该URL在文件中的相对位置
				public String getQuery(   )        获取该URL的查询名
			 */
			
			System.out.println(url.getProtocol());
			System.out.println(url.getHost());
			System.out.println(url.getPort());
			System.out.println(url.getPath());
			System.out.println(url.getFile());
			System.out.println(url.getRef());
			System.out.println(url.getQuery());
			
			// get 资源
			is = url.openStream();
			byte[] b = new byte[20];
			int len;
			while((len=is.read(b))!=-1){
				
				System.out.println(new String(b,0,len));
			}
			
			// set资源
			URLConnection urlconn = url.openConnection();
			isConn = urlconn.getInputStream();
			fos = new FileOutputStream(new File("abc.txt"));
			byte[] by = new byte[20];
			int lenConn;
			while((lenConn=isConn.read(by))!=-1){
				fos.write(by,0,lenConn);
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if(isConn!=null){
				try {
					isConn.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}
发布了30 篇原创文章 · 获赞 0 · 访问量 3679

猜你喜欢

转载自blog.csdn.net/MENGCHIXIANZI/article/details/104738376
今日推荐