这个demo前提是在tomcat服务器的webapps的example文件夹下新建一个HelloWorld.txt。并写入一写内容
package myNetDemo;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.junit.Test;
public class TestURL {
// URL统一资源定位符,一个URL对象,对应着互联网上的一个资源
// 可以通过URL对象调用其相应的方法,将此资源读取
public static void main(String[] args) {
// 创建一个url对象
URL url = null;
// 如何将服务端的资源读取进来:openStream()
InputStream iStream = null;
int len;
try {
url = new URL("http://127.0.0.1:8080/examples/HelloWorld.txt?a=b");
/*
* 个方法
*
* 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());//URL文件名
* System.out.println(url.getRef());//获取URL在文件中的相对位置
* System.out.println(url.getQuery());//获取URL查询名
*/
iStream = url.openStream();
byte[] b = new byte[20];
while ((len = iStream.read(b)) != -1) {
String string = new String(b, 0, len);
System.out.println(string);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if (iStream != null) {
try {
iStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 即要读进来资源又想写出去资源,:URLConnection
InputStream is = null;
FileOutputStream fos = null;
try {
url = new URL("http://127.0.0.1:8080/examples/HelloWorld.txt?a=b");
URLConnection connection = url.openConnection();
is = connection.getInputStream();
fos = new FileOutputStream(new File("out1.txt"));
byte[] b1 = new byte[20];
int len1;
while ((len1 = is.read(b1)) != -1) {
fos.write(b1, 0, len1);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}