IO流从url路径中获取内容保存到本地的文件中

 要点:

1.创建输出的文件目录与文件

2.输入输出流的同时运用以及char数组的缓存

3.关闭方法

package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;

public class save {
	public static void main(String [] args){
		//使用File类创建一个要操作的文件路径
		String savePath = "E:/aa/bbb/a.txt";
		File file = new File(savePath);
		//如果文件目录不出在则创建目录 *getParentFile()*
		if(!file.getParentFile().exists()){//判断文件目录是否存在
			file.getParentFile().mkdirs();//创建目录
		}
		
		//使用url 读取网页内容
		String path = "https://www.baidu.com/";
		//可以创建url实例
		URL url;
		try {
			url = new URL(path);
		//字节输入流
		InputStream is = url.openStream();
		//字节流转字符流
		InputStreamReader isr = new InputStreamReader(is,"UTF-8");
		//再转缓冲流  提高读取效率
		BufferedReader br = new BufferedReader(isr);
		
		//文件输出流
		OutputStream output = new FileOutputStream(file);
		//字符缓冲流输出                                                                       转化流
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(output));
		
		//使用char 数组传输    -----字节流byte数组
		char [] chs = new char[1024];
		//标记
		int len = 0;

		while((len = br.read(chs)) != -1){// read() 方法,读取输入流的下一个字节,返回一个0-255之间的int类型整数。如果到达流的末端,返回-1
			bw.write(chs, 0, len);//写入文件
			bw.flush();//清除缓存
		}
		
		close(bw,br);
		
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *关闭方法 
	 */
	private static void close (AutoCloseable ...ac ){
		for (AutoCloseable autoCloseable : ac) {
			if (autoCloseable != null) {
				try {
					autoCloseable.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_41648616/article/details/81558889