黑马程序员——Java基础--IO(三)

-----------android培训java培训、java学习型技术博客、期待与您交流!------------

第三讲 总结(常见代码重要知识点)

一、字节输入流

示例1、

package cn.itheima.FileInputStream;

import java.io.FileInputStream;
import java.io.IOException;

/*
 * 字节输入流读取任意文件
 * 创建FileInputStream 对象,传递字符串文件名
 * 调用父类方法read读取  int read()
 * 输出
 * 释放资源
 */
public class FileInputStreamDemo {
	public static void main(String[] args) throws IOException {
		//创建FileInputStream 对象
		FileInputStream  f = new FileInputStream("d:\\d.txt");
		//调用父类方法read读取
		//定义一个变量来接受读取到的字符串文件名
		int i = 0;
		//利用循环进行读取,循环结束条件 read()返回-1的时候
		while((i=f.read())!=-1){
			System.out.print((char)i);
		}
		//释放资源
		f.close();
	}
}

示例2、


package cn.itheima.FileInputStream;

import java.io.FileInputStream;
import java.io.IOException;

/*
 *  字节输入流 读取文件
 *  FileInputStream 方法read()
 *  传递字节数组 
 *    int read(byte[])
 *  数组的作用,int返回值表示什么意思
 *  读取的字节,存储到数组中
 *  int返回值 每次存储到数组中的有效字节个数
 *  
 *  数组缓冲技术,提高流的读取效率
 */
public class FileInputStreamDemo1 {
	public static void main(String[] args) throws IOException {
		//创建FileInputStream对象
		FileInputStream f = new FileInputStream("d:\\d.txt");
		//定义一个字节数组来存放
		byte[] bytes = new byte[1024];
		int i = 0;
		while((i=f.read(bytes))!=-1){
			System.out.println(new String(bytes, 0, i));
		}
		f.close();
	}
}

二、字节输出流

示例1、

package cn.itheima.FileOutputStream;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 *  字节输出流,写文件
 *  抽象基类OutputStream write
 *  找他的子类,创建子类的对象  FileOutputStream
 *  子类的构造方法
 *     传递File对象,File对象封装的是文件
 *     传递String文件名
 *  
 *  字节流写文件的实现步骤
 *    1, 创建字节输出流的子类对象
 *    2, 调用父类方法write
 *    3, 释放资源
 */
public class FileOutputStreamDemo {
	public static void main(String[] args) throws FileNotFoundException, IOException{
		//创建FileOutputStream子类对象,传递字符串文件名
		//创建子类对象,完成哪些事情
		//创建对象在堆里面,调用Windows底层功能,创建文件,如果有就覆盖
		//抛出异常
		FileOutputStream f = new FileOutputStream("d:\\d.txt");
		//写入单个字节
		f.write(97);
		//写入字节数组
		f.write("gfj\r\n".getBytes());
		f.write("gfj\r\n588\r\n".getBytes());
		//写入部分字节数组
		byte[] bytes = {102,103,104,105,106};
		f.write(bytes, 0, 3);
		f.close();
	}
}

示例2、

package cn.itheima.FileOutputStream;

import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 字节输出流,对于文件的追加写入
 * 创建FileOutputStream,覆盖文件效果
 * 构造方法,第二个参数,写true,追加写文件
 */
public class FileOutputStreamDemo1 {
	public static void main(String[] args) throws IOException {
		FileOutputStream f = new FileOutputStream("d:\\d.txt",true);
		f.write(97);
		f.close();
	}
}

三、四种复制文件的方式

1、字节流读写单个字节

package cn.itheima.copy;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 利用FileInputStream字节输入流读取文件源
 * 利用FileOutputStream字节输出流写入目的文件
 * read()
 * write()
 * 
 */
public class CopyDemo {
	public static void main(String[] args) {
		long l = System.currentTimeMillis();
		copy();
		long l1 = System.currentTimeMillis();
		System.out.println("复制的时间为:" + (l1 - l) + "毫秒");
	}

	public static void copy() {
		// 创建FileInputStream对象,读取数据源
		FileInputStream fis = null;
		// 创建FileOutputStream对象,写入数据目的
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("d:\\a.mp3");
			fos = new FileOutputStream("e:\\a.mp3");
			int len = 0;
			while ((len = fis.read()) != -1) {
				fos.write(len);
			}
		} catch (IOException ex) {
			// ex.printStackTrace();
			throw new RuntimeException("文件复制失败");
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("释放资源失败");
			} finally {
				try {
					if (fos != null) {
						fos.close();
					}
				} catch (IOException ex) {
					throw new RuntimeException("释放资源失败");
				}
			}
		}
	}
}

2、 字节流读写字节数组

package cn.itheima.copy;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 通过字节数组复制一首MP3到另一文件目录
 * 
 */
public class CopyMp3ArrayDemo {
	public static void main(String[] args) {
		long a = System.currentTimeMillis();
		copy_1();
		long b = System.currentTimeMillis();
		System.out.println("复制的时间为:"+(b-a)+"毫秒");
	}

	public static void copy_1() {
		// 创建FileInputStream对象,读取数据源
		FileInputStream fis = null;
		// 创建FileOutputStream 对象,写入目的数据
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("d:\\a.mp3");
			fos = new FileOutputStream("e:\\a.mp3");
			// 定义一个数组
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = fis.read(bytes)) != -1) {
				fos.write(bytes,0,len);
			}
		} catch (IOException ex) {
			throw new RuntimeException("MP3复制失败!");
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("释放资源失败");
			} finally {
				try {
					if (fos != null) {
						fos.close();
					}
				} catch (IOException ex) {
					throw new RuntimeException("释放资源失败");
				}
			}
		}
	}
}

字节缓冲流,字节流一次读写一个数组的速度明显比一次读写一个字节的速度快很多,这是加入了数组这样的缓冲区效果,java本身在设计的时候,也考虑到了这样的设计思想(装饰设计模式后面讲解),所以提供了字节缓冲区流。

分别是:

字节缓冲输出流:BufferedOutputStream
字节缓冲输入流:BufferedInputStream

3、字节流缓冲区读写单个字节

package cn.itheima.copy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 利用字节流缓冲区读取单个字节
 * 同时利用字节流缓冲区写单个字节 
 */
public class CopyBufferedDemo {
	public static void main(String[] args) {
		long a = System.currentTimeMillis();
		copy_2();
		long b = System.currentTimeMillis();
		System.out.println("复制的时间为:"+(b-a)+"毫秒");
	}

	public static void copy_2() {
		// 创建BufferedInputStream对象,读取数据源
		BufferedInputStream bis = null;
		// 创建BufferedOutputStream对象,写入目的数据
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream("d:\\a.mp3"));
			bos = new BufferedOutputStream(new FileOutputStream("e:\\a.mp3"));
			int len = 0;
			while ((len = bis.read()) != -1) {
				bos.write(len);
			}
		} catch (IOException ex) {
			throw new RuntimeException("MP3复制失败!");
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("释放资源失败");
			} finally {
				try {
					if (bos != null) {
						bos.close();
					}
				} catch (IOException ex) {
					throw new RuntimeException("释放资源失败");
				}
			}
		}
	}
}

4、字节流缓冲区读写字节数组

package cn.itheima.copy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 利用字节流缓冲区读取字节数组
 * 利用字节流缓冲区写入字节数组
 * 
 */
public class CopyMp3ArrayBufferedDemo {
	public static void main(String[] args) {
		long a = System.currentTimeMillis();
		copy_3();
		long b = System.currentTimeMillis();
		System.out.println("复制的时间为:"+(b-a)+"毫秒");
	}

	public static void copy_3() {
		// 创建BufferedInputStream对象,读取数据源,不要new
		BufferedInputStream bis = null;
		// 创建BufferedOutputStream对象,写入数据目的,不要new
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream("d:\\a.mp3"));
			bos = new BufferedOutputStream(new FileOutputStream("e:\\a.mp3"));
			// 定义一个字节数组
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = bis.read(bytes)) != -1) {
				bos.write(bytes,0,len);
			}
		} catch (IOException ex) {
			throw new RuntimeException("文件复制失败");
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("释放资源失败");
			} finally {
				try {
					if (bos != null) {
						bos.close();
					}
				} catch (IOException ex) {
					throw new RuntimeException("释放资源失败");
				}
			}
		}
	}
}

四、编码表、编码与解码

编码表:由字符及其对应的数值组成的一张表。

编码表由来:
        早期计算,电信号,开关,随后,出现了数字电路。0关1开,8个位置表示一个数组,后来,每个字符对应十进制数,97-->a 48-->0 65-->A;就出现了ASCII表。随后出现了中文编码表,GB2312-->8000个汉字,对其进行扩容,-->20000个汉字,操作系统编码表GBK,再次扩容,--GB18030;
        BIG5:繁体中文编码表;
        最后为了统一,出现了万国码表(Unicode),容纳全球所有的语言,char用的就是这个存储的,随后优化成UTF-8(三个字节对应1个汉字);
        特殊编码:ISO8859-1 拉丁文,JAVAEE学科Web互联网应用程序,服务器(Apache Tomcat 不认识中文);
    编码:
        String类方法getBytes() 字符串转成字节数组,使用默认的GBK
    解码:
        String类的构造方法,将字节数组变成字符串,使用默认的GBK
注意:编码和解码时表必须一致。

package cn.itheima.encoding;

import java.util.Arrays;



/*
 * 编码:String类中getBytes()字符串转成字节数组,使用默认的GBK
 * 		String的getBytes(String charsetname),
 * 		字符串转成字节数组,查询指定的编码表(比如UTF-8)
 * 解码:String类的构造方法,将字节数组变成字符串,使用默认的GBK
 * 		String类的构造方法,传递字节数组,传递字符串的编码表名字
 */
public class EncodingDemo {
	public static void main(String[] args) throws Exception {
//		method();
//		method_1();
//		method_2();
//		method_3();
		byte[] bytes = "琲".getBytes();
		for (byte b : bytes) {
			System.out.println(b);
		}
		String string = Arrays.toString(bytes);
		System.out.println(string);
	}
	/*
	 * 将字节数组转成字符串
	 * 查询指定编码表utf-8
	 */
	public static void method_3() throws Exception{
		//定义一个字节数组
		byte[] bytes = {-26,-78,-95,-26,-100,-119,-25,-69,-109,-26,-98,-100};
		String s = new String(bytes,"utf-8");
		System.out.println(s);
	}
	/*
	 * 将字节数组转成字符串
	 * 查询默认编码表GBK
	 */
	public static void method_2(){
		//定义一个字节数组
		byte[] bytes = {-29,-14,-42,-35,-44,-62,-71,-30};
		String s = new String(bytes);
		System.out.println(s);
	}
	/*
	 * 将字符串转成字节数组
	 * 查询UTF-8编码表
	 */
	public static void method_1() throws Exception{
		byte[] bytes = "没有结果".getBytes("utf-8");
		for (byte b : bytes) {
			System.out.println(b);
		}
	}
	/*
	 * 将字符串变成字节数组
	 * 默认编码表GBK
	 * 编码: 网络传输
	 */
	public static void method(){
		byte[] bytes = "泸州月光".getBytes();
		//遍历字节数组
		for (byte b : bytes) {
			System.out.println(b);
		}
		
	}
}

五、转换流

由于字节流操作中文不是特别方便,所以,java就提供了转换流。

字符流=字节流+编码表。

1、InputStreamReader


package cn.itheima.inputstreamreader;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/*
 * InputStreamReader (转换流)
 * 继承Reader 读取的方法read,单个字符,字符数组
 * InputStreamReader构造方法
 */
public class InputStreamReaderDemo {
	public static void main(String[] args) {
		// method();
		method_1();
	}

	/*
	 * 使用转换流+字节输入流读取文件 读取UTF-8编码文件
	 */
	public static void method_1() {
		// 创建转换流对象,不要new
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(new FileInputStream("d:\\a.txt"),
					"utf-8");
			int len = 0;
			/*
			 * while((len=isr.read())!=-1){ System.out.print((char)len); }
			 */
			char[] ch = new char[1024];
			while ((len = isr.read(ch)) != -1) {
				System.out.println(new String(ch, 0, len));
			}

		} catch (Exception e) {
			throw new RuntimeException("文件读取失败");
		} finally {
			try {
				if (isr != null) {
					isr.close();
				}
			} catch (Exception e) {
				throw new RuntimeException("释放资源失败");
			}

		}
	}

	/*
	 * 使用转换流+字节输入流读取文件 读取GBK编码的文件
	 */
	public static void method() {
		// 创建转换流对象,不要new
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(new FileInputStream("d:\\a.txt"));
			int len = 0;
			/*
			 * while((len=isr.read())!=-1){ System.out.print((char)len); }
			 */
			char[] ch = new char[1024];
			while ((len = isr.read(ch)) != -1) {
				System.out.println(new String(ch, 0, len));
			}
		} catch (Exception ex) {
			throw new RuntimeException("文件读取失败");
		} finally {
			try {
				if (isr != null) {
					isr.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("释放资源失败");
			}
		}
	}
}

2、OutputStreamWriter

package cn.itheima.outputstreamwriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class OutputStreamWriterDemo {
	public static void main(String[] args) {
		// method();
		method_1();
	}

	/*
	 * 转换流+字符输出流,写字符串 写UTF-8效果
	 */
	public static void method_1() {
		// 创建转换对象,字符转成字节,不要new
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream("d:\\a.txt"),
					"utf-8");
			osw.write("你好吗");
			osw.flush();
		} catch (IOException ex) {
			throw new RuntimeException("文件写入失败");
		} finally {
			try {
				if (osw != null) {
					osw.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("释放资源失败");
			}
		}
	}

	/*
	 * 转换流+字节输出流,写字符串 将字符串转成字节数组,写到字节输出流 写GBK的效果
	 */
	public static void method() {
		// 创建转换对象,字符转成字节,不要new
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(new FileOutputStream("d:\\a.txt"));
			osw.write("你好");
			osw.flush();
		} catch (IOException ex) {
			throw new RuntimeException("写入失败");
		} finally {
			try {
				if (osw != null) {
					osw.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("释放资源失败");
			}
		}
	}
}

3、转换流的文本复制

package cn.itheima.copy;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/*
 * 案例  转换流文本的复制
 * 
 */
public class CopyTranseDemo {
	public static void main(String[] args) {
		method();
	}

	/*
	 * 单个字符
	 */
	public static void method() {
		// 创建转换流对象,不要new
		InputStreamReader isr = null;
		OutputStreamWriter osw = null;
		try {
			isr = new InputStreamReader(new FileInputStream("d:\\a.txt"),"utf-8");
			osw = new OutputStreamWriter(new FileOutputStream("e:\\a.txt"),"utf-8");
			int len = 0;
			while ((len = isr.read()) != -1) {
				osw.write(len);
				osw.flush();
			}
		} catch (IOException ex) {
			throw new RuntimeException("复制文本失败");
		} finally {
			try {
				if (isr != null) {
					isr.close();
				}
			} catch (IOException ex) {
				throw new RuntimeException("释放资源失败");
			} finally {
				try {
					if (osw != null) {
						osw.close();
					}
				} catch (IOException ex) {
					throw new RuntimeException("释放资源失败");
				}
			}
		}
	}
}

-----------android培训java培训、java学习型技术博客、期待与您交流!------------


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值