字符流Reader-读取,输入
字符流Writer-写入,输出
文件字符流:
FileReader
FileWriter
使用步骤:
1.构建文件对象通过File类
2.将File类对象传递到字符流对象中
FileReader fr = new FileReader(file);
3.读取或者写入
读取:一次可以读取一个字符 read
一次可以读取一个字符数组 read(buf)
写入:
write(char)
write(char[] chs)
write(String str)
缓冲流
BufferedReader
BufferedWriter
readLine();//读取一行
newLine();//跨行
flush();//刷新缓冲区
转换流
InputStreamReader
OutputStreamWriter
网络编程
实现多台设备之间的数据交互
三要素:IP地址 端口号 网络通信传输协议
IP: InetAddress
端口号:
浏览器---80
tomcat--8080
sqlserver 1433
oracle 1521
网络通信传输协议(TCP|IP)
TCP
UDP
URL编程。
下载星博网站页面
// 1.通过URL对象定位到指定的资源处
URL url = new URL("file:///D:/xb/default.html");
// 2.通过url对象打开并且激活网络流
InputStream is = url.openStream();
// 3.获取到的字节输入流 转换成字符流 再转换成缓冲流
InputStreamReader isr = new InputStreamReader(is);
// 缓冲
BufferedReader br = new BufferedReader(isr);
// 定义一个字符串变量来拼接每一行读取的数据
StringBuffer sb = new StringBuffer();
// 每次读取一行数据
String content = "";
while (null != (content = br.readLine())) {
// System.out.println(content);
sb.append(content + "\n");
}
// 关闭流
br.close();
isr.close();
is.close();
String regex = "<img\\ssrc=\"([^\\\">]+)\"(\\swidth=\"\\w+\")?(\\sheight=\"\\w+\")?\\s/>";
//1.通过正则规则来实例化Pattern正则模式对象
Pattern compile = Pattern.compile(regex);
//2.通过compile模式对象创建Matcher对象
Matcher matcher = compile.matcher(sb);
//3.通过find方法以及group方法遍历查找到sb字符串中所有符合正则规则的内容(所有的img标签)
int count = 0;
while(matcher.find()) {
System.out.println(matcher.group(1));
count++;
//file:///D:/xb/images/btn_3.gif
//专门编写一个下载的方法 将matcher.group(1)文件名称作为参数传递
downLoadImage("file:///D:/xb/"+matcher.group(1));
}
System.out.println("图片总数: "+count);
}
private static void downLoadImage(String filePath) throws Exception {
//file:///D:/xb/images/btn_3.gif
//截取到图片名称
int index = filePath.lastIndexOf("/");
String fileName = "";
if(-1!=index) {
fileName = filePath.substring(index);
}
//1.创建URL对象将filePath传入定位资源
URL url = new URL(filePath);
//2.打开并激活网络流
InputStream is = url.openStream();
BufferedInputStream bis = new BufferedInputStream(is);
//3.输出流 写到本地去(下载)
File file = new File("D:\\"+fileName);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
//读取一个字节数组
byte[] bytes = new byte[1024];
int len = 0;
while(-1!=(len = bis.read(bytes))) {
bos.write(bytes, 0, len);
bos.flush();//刷新
}
bos.close();
fos.close();
bis.close();
is.close();
}