IO/拷贝文件的四种方法/解决乱码

161 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

IO概述

分类

IO流根据传输方向分为两种:输入流(读),输出流(写) 根据单位:字节流(java.io.InputStream,java.io.OutputStream),字符流(java.io.Reader,java.io.Writer) InputStream和OutputStream 上面是InputStream,下面是OutputStream σ_›σ 原谅我从网上随便抠的图☝☝☝

字节流(文本,图片,音频,视频)

在JDK中提供两个抽象类InputStream,OutputStream作为字节流的顶级父类。可以把InputStream,OutputStream比作两根水管。 InputStream输入管道,源设备--->程序 OutputStream输出管道,程序--->目标设备 最后一定要关闭管道!!避免浪费资源!! 下面是最完整的写法:

OutputStream out = null;
	try {
			out = new FileOutputStream(file);
			out.write(content.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {//finally一定会执行,所以在这里关流
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				out = null;//交付给gc
			}
		}

拷贝文件

public void copy_Paste(String srcPath,String destPath) throws Exception{
		
		FileInputStream fis = new FileInputStream(srcPath);
		FileOutputStream fos = new FileOutputStream(destPath);

下面提供4种方法进行拷贝

		/**1.一个个字节:效率低**/
		int data1 = fis.read();
		
		while(data1!=-1){
			fos.write((char)data1);
			data1 = fis.read();
		}
/**2.用一个数组作为缓冲**/
byte[] buff = new byte[1024];
		int total = fis.read(buff);
		while(total!=-1){
			fos.write(buff);
			total = fis.read(buff);
		}
	/**3.缓冲流**/
		BufferedInputStream bis = new BufferedInputStream(fis);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		int data2 = bis.read();
		while(data2!=-1){
			bos.write(data2);
			data2 = bis.read();
/**4.数据输入输出流**/
 DataInputStream dis = new DataInputStream(fis);//包装了fis
		DataOutputStream dos = new DataOutputStream(fos);
		int d = dis.readInt();
		dos.writeInt(d);
		while(dis.available()>0){
			d = dis.readInt();
			dos.writeInt(d);

        //关流 先关输入再关输出,不然水管会爆。。
        dis.close();
		dos.close();
		//由于DataInputStream,DataOutputStream是包装流
		//所以下面两行可以不用写
		fis.close();
		fos.close();

字符流(文本文件)

参考上面第四点

##标准输入输出流 在System类中定义了三个常量:in,out,err,它们被习惯性地称为标准输入输出流

常量 |类型 |流 |作用
-----------|-----|-----| in|InputStream|标准输入流|默认用于读取键盘输入的数据 out|PrintStream|标准输出流|默认将数据输出到命令行窗口 err|PrintStream|标准错误流|与out类似,通常输出的是应用程序运行时的错误信息

File类

File类用于封装一个路径

public void copy_Paste(String srcPath,String destPath) {
  copy_Paste(new  File(srcPath),new  File(destPath));
}

乱码问题

产生原因

字符=字节+编码

字节是计算机信息技术用于计量存储容量的一种计量单位,因此字节流也称为万能流 而编码方式不同,可能导致字符和字节的换算方式不同,可能1字符=2字节,也可能1字符=3字节


编码是将数据转化为二进制的过程,解码则是编码的逆过程 因此,乱码问题都出现在解码过程中


注意:下图字符集中只有GBK可以对汉字进行编码(以GB开头的编码方式都包含中文字符)

这里写图片描述

再比如:”中文”二字的GBK的字节流为d6 d0 ce c4,如果用utf-8(不支持中文)去解码,势必会乱码。

解决方法

  • 指定read,write编码

InputStreamReader(InputStream in, CharsetDecoder dec) 创建使用给定字符集解码器的 InputStreamReader。

OutputStreamWriter(OutputStream out, CharsetEncoder enc) 创建使用给定字符集编码器的 OutputStreamWriter。

  • 重新编码,怎么来怎么回

String(byte[] bytes, Charset charset) 通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。