功能
URL编程,从网络上读取数据;
代码
package com.demo;
import java.io.File;
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;
/**
*
* @author Lynn URL五部分: http://192.168.0.128:8080/helloworld/index.jsp
*
*/
public class Demo07 {
public static void main(String[] args) throws MalformedURLException {
// 资源的网络路径;
URL url = new URL("http://localhost:8080/Test/test.txt");
System.out.println("协议:" + url.getProtocol());
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());
//读入文件的内容有两种方法
//方法一
//获取输入流;
InputStream is = null;
FileOutputStream fos = null;
byte[] data;
int len;
try {
is = url.openStream();
fos = new FileOutputStream(new File("test1.txt"));
data = new byte[1024];
while((len=is.read(data))!=-1) {
fos.write(data, 0,len );
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.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();
}
}
}
//方法二
//输入流;
InputStream is1 = null;
//输出流;
OutputStream os = null;
try {
URLConnection urlConnection = url.openConnection();
is1 = urlConnection.getInputStream();
byte[] data1 = new byte[1024];
int len1 = 0;
while((len1=is1.read(data1))!=-1) {
System.out.println(new String(data1,0,len1));
}
// urlConnection.setDoOutput(true);
// os = urlConnection.getOutputStream();
//
// os.write("我是添加的内容".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(os!=null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(is1!=null) {
try {
is1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
运行结果
附
需要开启服务器,这里使用的是tomcat服务器。