几行代码在网上读写文件

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();
		}

总结

简单必须重复,重复还要用心。
用心创造快乐,坚持才能胜利。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值