java基于eclipse实现网络中读写文件
大家好,我是小鱼儿.yanxiao,非常荣幸各位来到我的博客。今天分享一波代码,若是喜欢本篇文章记得点赞加关注,我也会关注大家。欢迎大家发言,废话不多说走起。
前言
文章java代码版本"1.8.0_202"
本篇代码采用java装饰器类
提示:以下是本篇文章正文内容,下面案例可供参考!!
完整代码:
package chaper.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 从网络上读写文件
* 在给定的url读取文件内容,只支持HTTP协议
* @作者 YanXiaolxy
* @版本 2020.03
* @时间 2021年1月24日 下午10:34:39
*/
public class UrlTest {
static final String FilePath = "C:/Users/Administrator/Desktop/163index.Html";
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://www.163.com/index.html");
//将输出流转化为Reader的套路:使用装饰器类InputStreamReader,实现字节流和字符流之间的转换
StringBuffer content = new StringBuffer();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))){
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line);
content.append(line);
content.append(System.getProperty("line.separator"));
}
ReplaceLyriceDemo.WriteFileByPrintWriter(content.toString(), FilePath, false);
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码解读:
1.定义文件读入路径:
URL url = new URL("http://www.163.com/index.html");
2.定义文件写入路径:
static final String FilePath = "C:/Users/Administrator/Desktop/163index.Html";
3.使用装饰器类调用、转换:
//将输出流转化为Reader的套路:使用装饰器类InputStreamReader,实现字节流和字符流之间的转换
StringBuffer content = new StringBuffer();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))){
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line);
content.append(line);
content.append(System.getProperty("line.separator"));
}
ReplaceLyriceDemo.WriteFileByPrintWriter(content.toString(), FilePath, false);
} catch (IOException e) {
e.printStackTrace();
}
总结
简单必须重复,重复还要用心。
用心创造快乐,坚持才能胜利。