Java基础-IO流

异常

概述

  • 异常:就是程序出现了不正常的情况。
  • 例如:ArithmeticException:当出现异常的运算条件时,抛出此异常。例如,一个整数“除以0”时,抛出此类的一个实例。

如以下代码会出现ArithmeticException异常

public class ExceptionDemo {
	public static void main(String[] args) {
		method();
	}
	
	public static void method() {
		int a = 10;
		int b = 5;
		//b = 0;
		System.out.println(a/b);
	}
}

  • 常见的异常有:
    IndexOutOfBoundsException、NullPointerException、StringIndexOutOfBoundsException

继承体系

  1. Throwable 类是 Java 语言中所有错误或异常的超类。

  2. Error :是 Throwable 的子类,用于指示合理的应用程序不应该试图捕获的严重问题。也就是说针对程序发生了Error的情况,Java程序本身是无能为力的,比如说:硬件层面的问题,内存不足等。

  3. Exception 类及其子类:是 Throwable 的一种形式,它指出了合理的应用程序想要捕获的条件。 也就是说针对程序发生了Exception的情况,是我们需要处理的问题。

  • Exception的分类:
    运行期的异常(RunTimeException):在编译期是不处理的,在程序运行时候出现了问题,需要我们回来修改代码。
    编译期的异常(非RunTimeException):在编译期就必须处理,否则程序不能通过编译,就更不能正常的执行了。

JVM针对异常的默认处理方式

  1. 把异常的名称,异常的原因,异常出现的位置等信息在控制台输出
  2. 让程序停止执行

控制台输出:

java.lang.ArithmeticException:异常的类名,包括包名
 / by zero:异常的原因,被0除
at com.exer.ExceptionDemo2.method(ExceptionDemo2.java:17):异常的位置

异常处理方案

try catch

格式:

  •   try {
      	可能出现异常的代码;
      }catch(异常类名  变量名) {
      	异常的处理代码;
      }
    

执行流程:

  • 程序从try开始执行,执行中到哪里出现了问题,就会直接跳转到catch里面执行。
  • 执行完毕后,程序还能继续往下执行。

捕获异常后的处理方式:

  •   异常处理代码部分:
      public void printStackTrace():把异常的错误信息输出在了控制台。
    

try…catch处理方式&JVM的默认处理方式的不同:

  •   try..cathc处理方式:产生了问题, 是自己将问题处理掉, 并且不影响后续代码的运行
      JVM默认处理方式是将程序终止, 并将异常信息打印在控制台,这样会影响程序的继续执行
    

throws

格式:

  •   throws 异常类名
      注意:这个格式必须跟在方法的括号的后面
    

注意:

  • 编译时的异常是必须要进行处理的,有两种处理方案:try…catch…或者throws
  • 如果采用了throws的方案,则将来谁调用,还得再进行处理。
  • 运行时异常可以不用处理,出现问题后我们需要回来修改代码

示例:

public class ExceptionDemo5 {
	public static void main(String[] args) {
		System.out.println("程序开始执行");
		try {
			method();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		method2();
		System.out.println("程序结束执行");
	}
	
	//编译时异常
	public static void method() throws ParseException {
		String s = "2088-08-08";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d = sdf.parse(s);
		System.out.println(d);
	}
	
	//运行时异常
	public static void method2() throws ArithmeticException {
		int a = 10;
		int b = 0;
		System.out.println(a/b);
	}	
}

异常分类

  • Java中的异常被分为两大类:编译时异常和运行时异常
  • 所有的RuntimeException类及其子类的实例被称为运行时异常,其他的异常都是编译时异常

编译时异常

Java程序必须显示且处理,否则程序就会发生错误的一个提示,无法通过编译

运行时异常

Java程序无需显示处理,同时也可以和编译时异常一样处理

示例

public class ExceptionDemo4 {
	public static void main(String[] args) {
		System.out.println("程序开始执行");
		//method();
		method2();
		System.out.println("程序结束执行");
	}
	
	//编译时异常ParseException
	public static void method() {
		try{
			//String s = "2088-08-08";
			String s = "abcd";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date d = sdf.parse(s);
			System.out.println(d);
		}catch(ParseException e) {
			e.printStackTrace();
		}
	}
	
	//运行时异常
	public static void method2() {
		try{
			int a = 10;
			int b = 0;
			System.out.println(a/b);
		}catch(ArithmeticException e) {
			e.printStackTrace();
		}
	}
}

File类

概述

  • File类:文件和目录路径名的抽象表示形式
  • 也就是说文件和目录是可以通过File封装成对象的
  • 目录:其实就是文件夹

构造方法

  • File(String pathname):通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。
  • File(String parent, String child):根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
  • File(File parent, String child):根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例

示例

public class FileDemo {
	public static void main(String[] args) {
		//File(String pathname)
		File f1 = new File("d:\\aa\\b.txt");
		//f1 指向了b.txt对象
		
		//File(String parent, String child)
		File f2 = new File("d:\\aa","b.txt");
		
		//File(File parent, String child)
		File f3 = new File("d:\\aa");
		File f4 = new File(f3,"b.txt");
		
		//上面的f1,f2,f4其实做的是同样的事情,就是把d:\\aa\\b.txt转换为了一个File对象
	}
}

路径问题

  • 绝对路径:是以盘符开始的路径。
  •   如“d:\\aa\\b.txt”
    
  • 相对路径:不以盘符开始。是相对于当前的项目所在位置而言的,在项目的目录下。
  •   如“b.txt”
    

创建功能

  • public boolean createNewFile():创建文件
    如果文件不存在,创建文件并返回true
    如果文件存在,创建文件失败并返回false

  • public boolean mkdir():创建目录(文件夹)
    如果目录不存在,创建目录并返回true
    如果目录存在,创建目录失败并返回false

  • public boolean mkdirs():创建多级目录

示例

public class FileDemo {
	public static void main(String[] args) throws IOException {
		//需求1:我要在d盘目录下创建一个文件a.txt
		File f1 = new File("d:\\a.txt");
		System.out.println("createNewFile:"+f1.createNewFile());
		
		//需求2:我要在d盘目录下创建一个目录bb
		File f2 = new File("d:\\bb");
		System.out.println("mkdir:"+f2.mkdir());
		System.out.println("-----------------");
		
		//需求3:我要在d盘目录下创建一个多级目录cc\\dd
		File f3 = new File("d:\\cc\\dd");
		System.out.println("mkdirs:"+f3.mkdirs());
		
		//需求4:我要在d盘目录下创建一个文件ee\\f.txt
		File f4 = new File("d:\\ee"); //f4指向ee目录,先创建ee文件夹
		File f5 = new File("d:\\ee\\f.txt"); //f5指向f.txt文件,后创建txt文件
		System.out.println("mkdir:"+f4.mkdir());
		System.out.println("createNewFile:"+f5.createNewFile());
	}
}

删除功能

  • public boolean delete():删除文件和目录

  • 注意
    如果一个目录中有内容(目录,文件),就不能直接删除。
    需要先删除目录中的内容,最后才能删除目录。

示例

public class FileDemo {
	public static void main(String[] args) throws IOException {
		// public boolean delete():删除文件和目录
		// 需求1:删除a.txt这个文件
		File f1 = new File("a.txt");
		System.out.println("delete:" + f1.delete());
		
		//需求2:我要删除bb这个目录
		File f2 = new File("bb");
		System.out.println("delete:"+f2.delete());
		System.out.println("--------------------");
		
		//需求3:我要删除cc这个目录
		File f3 = new File("cc");
		File f4 = new File("cc\\d.txt");
		//错误的做法:System.out.println("delete:"+f3.delete());
		//思路:先删除d.txt这个文件,再删除cc这个目录
		f4.delete();
		f3.delete();
	}
}

判断功能

  • public boolean isDirectory():判断是否是目录
  • public boolean isFile():判断是否是文件
  • public boolean exists():判断是否存在

获取功能

  • public String getAbsolutePath():获取绝对路径
  • public String getPath():获取相对路径
  • public String getName():获取名称

IO

概述

	I   ----   Input	  -> 输入  --读取
	O  ----   Output      -> 输出  --写出
  • 读取和写出都是针对数据而言的, 所以, IO流就是用来处理设备之间的数据传输问题的

  • 常见应用:文件复制;文件上传;文件下载

分类

按照类型分:

  •   字节流
    
  •   字符流	(字符流数据通过Windows自带的记事本软件打开是可以读懂里面内容的)
    

按照流向分:

  •   输入流	: 用来读取数据的:
    
  •   输出流 : 用来写出数据的
    

字节流&字符流抽象超类

字节流:

  •   InputStream	:	字节输入流
      OutputStream	:	字节输出流
    

字符流:

  •   Reader :字符输入流
      Writer	:字符输出流
    

字节流

FileOutputStream

概述:

  • OutputStream:此抽象类是表示输出字节流的所有类的超类
  • FileOutputStream:文件输出流是用于将数据流出写入 File的

构造方法

  • FileOutputStream(String name):创建一个向具有指定名称的文件中写入数据的输出文件流。

写数据的步骤

  1. 创建字节输出流对象
  2. 调用写数据的方法
  3. 释放资源

示例:

public class FileOutputStreamDemo {
	public static void main(String[] args) throws IOException {
		//创建字节输出流对象
		FileOutputStream fos = new FileOutputStream("a.txt");
		/*
		 * 创建字节输出流对象做了这样的三件事情:
		 * A:调用系统功能创建了文件
		 * B:创建字节输出流对象
		 * C:让fos这个对象指向a.txt这个文件
		 */
		
		//write(int b) 
		fos.write(65);
		fos.write(66);
		
		//注意:最后需要释放资源
		//close() 关闭此文件输出流并释放与此流有关的所有系统资源。
		fos.close();
	}
}

写数据的3种方式

写出数据的三个方法:

  • public void write(int b):一次写一个字节
  • public void write(byte[] b):一次写一个字节数组
  • public void write(byte[] b,int off,int len):一次写一个字节数组的一部分

String类中的方法:

  • byte[] getBytes() : 将字符串转换为字节数组 String–byte[]

示例

public class FileOutputStreamDemo2 {
	public static void main(String[] args) throws IOException {
		//创建字节输出流对象
		//FileOutputStream(String name) 
		FileOutputStream fos = new FileOutputStream("b.txt");
		
		//public void write(int b):一次写一个字节
		fos.write(65);
		
		//public void write(byte[] b):一次写一个字节数组
		byte[] bys = {65,66,67,68,69};
		fos.write(bys);
		
		//需求:写入一个字符串数据
		//String -- byte[]
		//String类中有一个方法:public byte[] getBytes()
		//byte[] bys = "ABCDE".getBytes();
		//fos.write(bys);
		fos.write("ABCDE".getBytes());
		
		//public void write(byte[] b,int off,int len):一次写一个字节数组的一部分
		fos.write("ABCDE".getBytes(),0,3); //写进了ABC
		
		//释放资源
		fos.close();
	}
}

实现换行

不同的操作系统,针对换行的符号识别是不一样的。

  • windows:\r\n
  • linux:\n
  • mac:\r
追加数据

用构造方法带第二个参数是true的情况:

  • FileOutputStream(String name, boolean append)
  •   如:FileOutputStream fos = new FileOutputStream("c.txt",true);
      //如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处
    

示例

public class FileOutputStreamDemo3 {
	public static void main(String[] args) throws IOException {
		//创建字节输出流对象
		//FileOutputStream fos = new FileOutputStream("c.txt");
		FileOutputStream fos = new FileOutputStream("c.txt",true);
		
		//调用写数据的方法
		for(int x=0; x<10; x++) {
			fos.write("hello".getBytes());
			//加入换行符号
			fos.write("\r\n".getBytes());
		}
		
		//释放资源
		fos.close();
	}
}
写数据加入异常处理
  • try…catch…finally

  • 格式:
    try{
    可能发生问题的代码
    }catch(){
    处理异常代码
    }finally{
    一定会被执行的代码. // 通常用于释放资源, 做善后的动作
    }

  • 示例:

public class FileOutputStreamDemo4 {
	public static void main(String[] args) {
		FileOutputStream fos = null;
		try{
			//FileOutputStream fos = new FileOutputStream("d.txt");
			//fos = new FileOutputStream("z:\\d.txt");
			fos = new FileOutputStream("d.txt");
			fos.write("hello".getBytes());
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			if(fos!=null) {
				//释放资源
				try {
					fos.close(); //在null上调用方法会发生空指针异常
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

FileInputStream

读数据的步骤:

	A:创建字节输入流对象
	B:调用读数据的方法
	C:释放资源

读数据的方式

  1. 方式1:一次读取一个字节:
public class FileInputStreamDemo {
	public static void main(String[] args) throws IOException {
		//创建字节输入流对象
		FileInputStream fis = new FileInputStream("a.txt");
		int by;
		
		// 用by不断的记录读取到的每一个数据
		while((by=fis.read())!=-1) {
			System.out.print((char)by);
		}
		//释放资源
		fis.close();
	}
}
  1. 方式2: 一次读取一个字节数组
  • public int read(byte[] b):
    从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中
    返回值是读入缓冲区的字节总数,也就是实际的读取个数
    如果因为已经到达文件末尾而没有更多的数据,则返回 -1。

  • 示例

public class FileInputStreamDemo2 {
	public static void main(String[] args) throws IOException {
		//创建字节输入流对象
		FileInputStream fis = new FileInputStream("b.txt");
		byte[] bys = new byte[1024]; //1024或者1024的整数倍
		int len;
		//将数据读取到数组中, 并用len记录读取到的有效字节个数
		while((len=fis.read(bys))!=-1) {
			System.out.print(new String(bys,0,len));
		}
		//释放资源
		fis.close();
	}
}

练习

复制文本文件
  • 思路:
  1. 创建输入输出流对象关联数据源和数据目的
  2. 定义字节数组(为了提高效率)
  3. 将数据通过 while 循环不断读取到字节数组中
  4. 将数据从字节数组中取出并写出
  5. 释放资源
  • 示例:
public class CopyTxtTest {
	public static void main(String[] args) throws IOException {
		//封装数据源
		FileInputStream fis = new FileInputStream("d:\\1.txt");
		//封装目的地
		FileOutputStream fos = new FileOutputStream("2.txt");
		
		//读数据方式2:一次读取一个字节数组
		byte[] bys = new byte[1024];
		int len; //读取到的实际长度
		while((len=fis.read(bys))!=-1) {
			fos.write(bys, 0, len); //写入实际读取的长度
		}
		
		//释放资源
		fos.close();
		fis.close();
	}
}

复制图片
  • 思路:(同上)

  • 示例:

public class CopyJpgTest {
	public static void main(String[] args) throws IOException {
		// 封装数据源
		FileInputStream fis = new FileInputStream("d:\\mn.jpg");
		// 封装目的地
		FileOutputStream fos = new FileOutputStream("mn.jpg");

		// 读写数据
		// 方式2:一次读取一个字节数组,一次写一个字节数组的一部分
		byte[] bys = new byte[1024];
		int len;
		while ((len = fis.read(bys)) != -1) {
			fos.write(bys, 0, len);
		}

		// 释放资源
		fos.close();
		fis.close();
	}
}

字节缓冲区流

  • 概述:字节流一次读写一个数组的速度比一次读写一个字节的速度快很多,这是加入了数组这样的缓冲区效果,java本身在设计的时候,也考虑到了这样的设计思想,所以提供了字节缓冲区流

  • 作用:字节缓冲区流仅仅是提供了缓冲区(而真正的底层的读写数据还得需要基本的流对象进行操作)

  • 分类:

  •   BufferedOutputStream:字节缓冲输出流
      BufferedInputStream:字节缓冲输入流
    
  • 使用示例:

public class BufferedStreamDemo {
	public static void main(String[] args) throws IOException {
		//创建字节缓冲输出流对象
		// BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.txt"));
		// bos.write("hello".getBytes());
		// bos.close();

		//创建字节缓冲输入流对象
		// BufferedInputStream(InputStream in)
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));
		
		//方式1:一次读取一个字节
		int by;
		while((by=bis.read())!=-1) {
			System.out.print((char)by);
		}
		
		//方式2:一次读取一个字节数组
		byte[] bys = new byte[1024];
		int len;
		while((len=bis.read(bys))!=-1) {
			System.out.print(new String(bys,0,len)); //用String的构造方法将byte数组转成String输出
		}
		
		//释放资源
		bis.close();
	}
}

字符流

概述

  • 出现的原因:字节流一次读取一个字节的方式当 读取带有汉字的文件是有问题的,因为读取到一个字节后就转为字符在控制台输出了,而汉字是由2个字节组成的,所以出现问题。
  • 例如下面的代码:
public class FileInputStreamDemo {
	public static void main(String[] args) throws IOException {
		//String s = "hello";
		//[104, 101, 108, 108, 111]
		String s = "你好";
		//[-60, -29, -70, -61]
		byte[] bys = s.getBytes();
		System.out.println(Arrays.toString(bys));
	}
}

转换流 = 字节流 + 编码表

  • 转换流其实就是一个字符流。
  • 转换流的名字比较长,为了简化书写,转换流提供了对应的子类。
  •   OutputStreamWriter --- FileWriter
      InputStreamReader --- FileReader
    

编码表

概述:由字符及其对应的数据组成的一张表

  •   例如:ASCII:
      		‘a’	97
      		‘A’	65
      		‘0’	48
    

常见编码表

  • ASCII : 美国标准信息交换码, 用一个字节的7位表示数据
  • ISO-8859-1 : 欧洲码表, 用一个字节的8位表示数据, 兼容ASCII
  • GB2312 : 中文码表的升级版, 融合了更多的中文文字符号, 兼容ASCII
  • UTF-8 : 是一种可变长度的字符编码, 用1-3个字节表示数据, 又称为万国码, 兼容ASCII,用在网页上可以统一页面中的中文简体繁体和其他语言的显示

乱码问题
针对同一个数据, 采用的编码和解码方案不一致导致的

String类的编码和解码

编码:把看得懂的变成看不懂的

  • public byte[] getBytes(String charsetName) throws UnsupportedEncodingException:使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。

解码:把看不懂的变成看得懂的

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

注意:编码和解码的方式需要一致!

示例:

public class StringDemo {
	public static void main(String[] args) throws UnsupportedEncodingException {
		//定义一个字符串
		String s = "你好";
		
		//编码
		//byte[] bys = s.getBytes();//使用平台的默认字符集将此 String 编码为 byte 序列
		//默认编码是GBK
		//[-60, -29, -70, -61]
		//byte[] bys = s.getBytes("GBK"); //指定编码GBK
		//[-60, -29, -70, -61]
		byte[] bys = s.getBytes("UTF-8"); //指定编码UTF-8
		//[-28, -67, -96, -27, -91, -67]
		System.out.println(Arrays.toString(bys));
		
		//解码
		//String ss = new String(bys); //通过使用平台的默认字符集解码指定的 byte 数组
//		String ss = new String(bys,"GBK");//指定编码GBK
		String ss = new String(bys,"UTF-8");//指定编码UTF-8
		System.out.println(ss);
	}
}

构造方法

OutputStreamWriter 字符输出流

  • public OutputStreamWriter(OutputStream out):根据默认编码把字节流的数据转换为字符流
  • public OutputStreamWriter(OutputStream out,String charsetName):根据指定编码把字节流数据转换为字符流

InputStreamReader 字符输入流

  • public InputStreamReader(InputStream in):用默认的编码读数据
  • public InputStreamReader(InputStream in,String charsetName):根据指定编码方式读数据

转换流的编码和解码

转换流其实就是一个字符流。
转换流 = 字节流 + 编码表

示例

public class ConversionStreamDemo {
	public static void main(String[] args) throws IOException {
		//public OutputStreamWriter(OutputStream out):默认编码GBK
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"),"UTF-8");
		
		//调用写数据的方法
		osw.write("你好");
		//释放资源
		osw.close();
		
		//public InputStreamReader(InputStream in):默认编码GBK
		InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"),"UTF-8");
		
		//读数据:一次读取一个字符数据
		int ch;
		while((ch=isr.read())!=-1) {
			System.out.print((char)ch);
		}
		//释放资源
		isr.close();
	}
}

OutputStreamWriter

写数据的5种方式

  • public void write(int c):写一个字符
  • public void write(char[] cbuf):写一个字符数组
  • public void write(char[] cbuf,int off,int len):写一个字符数组的一部分
  • public void write(String str):写一个字符串
  • public void write(String str,int off,int len):写一个字符串的一部分

示例

public class OutputStreamWriterDemo {
	public static void main(String[] args) throws IOException {
		//创建字符输出流对象
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("b.txt"));
		
		//public void write(int c):写一个字符
//		osw.write(97);
//		osw.write('a');
		//写完数据后,没有发现数据,为什么呢?
		//1字符=2字节
		//文件中的数据存储的基本单位是字节
		
		//public void write(char[] cbuf):写一个字符数组
//		char[] chs = {'a','b','c','d','e'};
//		osw.write(chs);
		
		//public void write(char[] cbuf,int off,int len):写一个字符数组的一部分
//		char[] chs = {'a','b','c','d','e'};
//		osw.write(chs, 1, 3);
		
		//public void write(String str):写一个字符串
//		osw.write("hello");
		
		//public void write(String str,int off,int len):写一个字符串的一部分
		osw.write("hello", 0, 3);
		
//		//void flush():刷新该流的缓冲
//		osw.flush();
//		
//		//释放资源
		osw.close(); //关闭此流,但要先刷新它
	}
}

InputStreamReader

读数据的5种方式:

  • public int read():一次读取一个字符
  • public int read(char[] cbuf):一次读取一个字符数组

示例:

public class InputStreamReaderDemo {
	public static void main(String[] args) throws IOException {
		//创建字符输入流对象
//		InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"));
		InputStreamReader isr = new InputStreamReader(new FileInputStream("OutputStreamWriterDemo.java"));
		
		//public int read():一次读取一个字符
//		int ch;
//		while((ch=isr.read())!=-1) {
//			System.out.print((char)ch);
//		}
		
		//public int read(char[] cbuf):一次读取一个字符数组
		char[] chs = new char[1024];
		int len;
		while((len=isr.read(chs))!=-1) {
			System.out.print(new String(chs,0,len));
		}
		
		//释放资源
		isr.close();
	}
}

字符缓冲区流

概述

  • BufferedWriter:将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。
  • BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。

注意

  • 可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了。
  • OutputStreamWriter — FileWriter — BufferedWriter
    InputStreamReader — FileReader — BufferedReader

构造方法

  • BufferedWriter(Writer out)
  • BufferedReader(Reader in)

使用示例

public class BufferedStreamDemo {
	public static void main(String[] args) throws IOException {
//		//创建字符缓冲输出流对象
//		BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
//		//调用写数据的方法
//		bw.write("hello");
//		//释放资源
//		bw.close();
		
		
		//创建字符缓冲输入流对象
		BufferedReader br = new BufferedReader(new FileReader("BufferedStreamDemo.java"));
		
		//一次读取一个字符数组
		char[] chs = new char[1024];
		int len;
		while((len=br.read(chs))!=-1) {
			System.out.print(new String(chs,0,len));
		}
		
		//释放资源
		br.close();
	}
}

特殊功能

BufferedWriter

  • void newLine():写入一个行分隔符,这个行分隔符是由系统决定的

BufferedReader

  • String readLine():包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null

案例:使用特殊功能复制java文件

public class CopyJavaTest {
	public static void main(String[] args) throws IOException {
		//封装数据源
		BufferedReader br = new BufferedReader(new FileReader("BufferedStreamDemo.java"));
		//封装目的地
		BufferedWriter bw = new BufferedWriter(new FileWriter("Copy.java"));
		
		//读写数据
		String line;
		while((line=br.readLine())!=null) {
			bw.write(line);
			bw.newLine();
			bw.flush();
		}
		
		//释放资源
		bw.close();
		br.close();

字符流练习

使用5种方式复制文本文件

分析5种方式分别是:

  1. 基本字符流一次读写一个字符
  2. 基本字符流一次读写一个字符数组
  3. 缓冲字符流一次读写一个字符
  4. 缓冲字符流一次读写一个字符数组
  5. 缓冲字符串一次读写一个字符串

示例:

public class CopyFileTest {
	public static void main(String[] args) throws IOException {
		method1();
		// method2();
		// method3();
		// method4();
		// method5();
	}
	
	//缓冲字符流一次读写一个字符串
	private static void method5() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("d:\\林青霞.txt"));
		BufferedWriter bw = new BufferedWriter(new FileWriter("窗里窗外.txt"));
		
		String line;
		while((line=br.readLine())!=null) {
			bw.write(line);
			bw.newLine();
			bw.flush();
		}
		
		bw.close();
		br.close();
	}
	
	//缓冲字符流一次读写一个字符数组
	private static void method4() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("d:\\林青霞.txt"));
		BufferedWriter bw = new BufferedWriter(new FileWriter("窗里窗外.txt"));
		
		char[] chs = new char[1024];
		int len;
		while((len=br.read(chs))!=-1) {
			bw.write(chs, 0, len);
		}
		
		bw.close();
		br.close();
	}
	
	//缓冲字符流一次读写一个字符
	private static void method3() throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("d:\\林青霞.txt"));
		BufferedWriter bw = new BufferedWriter(new FileWriter("窗里窗外.txt"));
		
		int ch;
		while((ch=br.read())!=-1) {
			bw.write(ch);
		}
		
		bw.close();
		br.close();
	}
	
	// 基本字符流一次读写一个字符数组
	private static void method2() throws IOException {
		FileReader fr = new FileReader("d:\\林青霞.txt");
		FileWriter fw = new FileWriter("窗里窗外.txt");

		char[] chs = new char[1024];
		int len;
		while((len=fr.read(chs))!=-1) {
			fw.write(chs, 0, len);
		}

		fw.close();
		fr.close();
	}

	// 基本字符流一次读写一个字符
	private static void method1() throws IOException {
		FileReader fr = new FileReader("d:\\林青霞.txt");
		FileWriter fw = new FileWriter("窗里窗外.txt");

		int ch;
		while ((ch = fr.read()) != -1) {
			fw.write(ch);
		}

		fw.close();
		fr.close();
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值