天天看点

Lesson_for_java_day16--java中的异常和IO流(File类、字节流、字符流、指定编码格式)

一、异常:

--------------------------------java中的异常-------------------------------------------

什么是异常:异常是中断了正常指令流的事件。

异常的由来:
	出现问题也是现实生活中一个具体的事物,也可以通过java的类的形式进行描述,并封装成对象,其实就是java
		对不正常情况进行描述后的对象体现。
		
异常的分类:(Throwable)
	|--Exception:异常
		|--checkException:编译时检测的异常。
		|--RuntimeException(uncheckException):运行时异常,编译时不检测的异常。
	|--Error:错误
	
RuntimeException:是一个特殊子类异常:
	1、如果在函数内抛出该异常,函数可以不用声明,编译一样通过。
	2、如果在函数上声明了异常,调用者可以不进行处理,编译一样通过,之所以不用在函数内声明,是因为不需要
		让调用者处理。当该异常发生时,希望程序停止,因为程序已经无法继续运算,希望停止后对代码进行修正。
		
对异常的处理方式:
	当程序有可能发生异常时,需要用throw或throws对异常进行抛出。
		1、throws用于函数上,throw用于函数内。
		2、throws后面跟异常类,可以跟多个,用逗号隔开,throw后面跟异常对象。
	对程序抛出的异常的处理方式:
		格式1:try{	} catch(  ){	} finally{	}
		格式2:try{	} catch(  ){	}
		格式3:try{	} finally{	}
	程序中,有catch就叫有对问题进行处理,没有catch就代表问题没有处理。如果异常是检测异常就必须声明。
	1、声明异常时,建议声明更为具体的异常,这样可以处理得更具体。
	2、对方声明了几个异常,就对应几个catch块,不要定义多余的catch块,如果多个catch块中的异常出现继承关系,
		父类异常catch块放在最后面。
	3、在进行catch处理时,一定要定义具体的处理方式,不要简单的定义一句e.printStackTrace();也不要简单打印
		一条输出语句。
		
异常类里的方法:
	getMessage():得到异常信息。
	toString():得到异常信息名称和异常信息。
	printStackTrace():得到异常信息名称、异常信息和异常出现的位置。
		JVM默认处理异常就是调用printStackTrace()方法,打印异常在堆栈的跟踪信息。
		
自定义异常:必须是自定义类继承Exception
	原因:异常体系有一个特点:因为异常类和异常对象都被抛出。他们都具有可抛性,这是throwable这个体系中独有的
		特性,只有这个体系中的类和对象可以被throw和throws操作。
	自定义异常时,如果该异常发生后无法再继续运算,就让这个异常继承RuntimeException.
	
异常在子父类覆盖中的体现:
	1、子类在覆盖父类时,如果父类的方法抛出异常,那么子类的覆盖方法只能抛出父类的异常或该异常的子类或处理掉异常。
	2、如果父类方法抛出多个异常,那么子类在覆盖该方法时,只能抛出父类异常的子集。
	3、如果父类或接口的方法中没有异常抛出,那么子类在覆盖方法时,也不可以抛出异常,如果子类方法出现异常,就必须
		进行try处理,绝对不能抛。
	
           

二、IO流:

流操作的基本规律:
		最痛苦的就是流对象很多,不知道该用哪一个。
		通过三个明确来完成:
			1、明确源和目的。
				源:输入流。InputStream   Reader
				目的:输出流。 OutputStream   Writer.
			2、操作的数据是否是纯文本。
				是:字符流
				不是:字节流
			3、当体系明确后,在明确要使用哪个具体的对象
				通过设备来进行区分:
					源设备:内存,键盘,硬盘
					目的设备:内存,硬盘,控制台
	IO流常用基类:
		字节流的抽象基类:
			InputStream, OutputStream
		字符流的抽象基类:
			Reader, Writer
		注:由这四个类派生出来的子类名称都是以其父类名称作为子类名的后缀。
			eg:InputStream的子类FileInputStream.
				Reader的子类FileReader.
	
	先学习字符流的特点:
		既然IO流是用于操作数据的,那么数据的最常见体现形式是:文件
		需要:在硬盘上创建一个文件并写入一些文字数据。
			找到一个专门用于操作文件的write子类对FileWriter。
			后缀名是父类名,前缀名是该流对象的的功能。
           

File类:

package cn.imcore.file;
/*
	File类常见方法:
		1、创建:
			boolean createNewFile();在指定位置创建文件,如果该文件已经存在,
				则不创建,返回false。这个和输出流不一样,输出流对象一建立创建
				文件,而文件已经存在,会覆盖
			boolean mkdir();创建一级文件夹目录
			boolean mkdirs();创建多级文件夹目录		
		2、删除:
			boolean delete();删除失败时返回false
			void deleteOnExit();在程序退出时删除指定文件
		3、判断:
			canExecute();是否可执行
			canRead();是否可读
			canWrite();是否可写
			compareTo(File pathname);比较路径名
			exists();文件是否存在(在判断文件是否是目录或文件时,必须先要判断
				该文件对象封装的内容是否存在)
			boolean isDirectory();是否是目录
			boolean isFile();是否是文件
			boolean isHidden();是否是隐藏文件
			boolean isAbsolute();判断是否是绝对路径
		4、获取信息:
			getName();获取文件名
			getPath();获取文件路径
			getParent();该方法返回的是绝对路径中的父目录,如果获取的是相对路径,返回null
				如果相对路径中有上一层目录,那么该目录就是返回结果
			
			String getAbsolutePath();返回绝对路径字符串
			long lastModified();返回最后修改时间
			long length();返回文件长度
			boolean renameTo(File dest);重新命名文件名
 */
import java.io.File;

public class Test1 {

	public static void main(String[] args) {
//		File f = new File("D:\\java基础\\day13\\temp.txt");
		File f = new File("D:/java基础/day13/temp.txt");
		
		System.out.println(File.separator);
		System.out.println("文件是否存在:" + f.exists());
		System.out.println("文件是否可读:" + f.canRead());
		System.out.println("文件是否可写:" + f.canWrite());
		System.out.println("是否是目录:" + f.isDirectory());
		System.out.println("是否是文件:" + f.isFile());
		System.out.println("文件长度:" + f.length());
		System.out.println("文件名:" + f.getName());
		System.out.println("文件路径:" + f.getPath());	
		System.out.println("上级目录:" + f.getParent());
				
	}
}
           

字节流输入:

package sonyi;

//字节流练习

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

public class Exercise {
	public static void main(String[] args) {
		File fileOut = new File("test/textOut.txt");
		File fileIn = new File("test/textIn.txt");
		System.out.println(fileOut.exists());
		if(!fileOut.exists()){
			try {
				fileOut.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(!fileIn.exists()){
			try {
				fileIn.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		fileStream(fileOut, fileIn);
		
	}
	
	public static void fileStream(File fileOut,File fileIn){
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(fileOut);
			fileInputStream = new FileInputStream(fileIn);
			byte[] temp = new byte[1024];
			int len = 0;
			while((len = fileInputStream.read(temp)) != -1){		
				fileOutputStream.write(temp,0,len);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			if(fileInputStream != null)
				try {
					fileInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if(fileOutputStream != null)
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
		}
	}
}
           

字符流输入:

package sonyi;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//字符流练习
public class Exercise {

	public static void main(String[] args) {
		File fIn = new File("sonyi/fIn.txt");
		File fOut = new File("sonyi/fOut.txt");
		
		if(!fIn.exists()){
			try {
				fIn.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(!fOut.exists()){
			try {
				fOut.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		readAndWrite(fIn, fOut);
	}
	
	public static void readAndWrite(File fIn,File fOut){
		FileReader fileReader = null;
		FileWriter fileWriter = null;
		
		try {
			fileReader = new FileReader(fIn);
			fileWriter = new FileWriter(fOut);
			char[] temp = new char[1024];
			while((fileReader.read(temp)) != -1){
				fileWriter.write(temp,0,temp.length);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			if(fileReader != null)
				try {
					fileReader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if(fileWriter != null){
				try {
					fileWriter.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}	
	}
}
           

指定文件编码:

package sonyi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Exercise4 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File fIn = new File("exercise4/utf-8.txt");
		File fOut = new File("exercise4/gbk.txt");
		//第一步:将utf-8的内容复制到gbk中
		copy(fIn, fOut);
		
		//第二步:在gbk末尾追加内容
//		append(fOut, "你好,很高兴见到你!");
//		append(fOut, "欢迎光临,下次再来!");
		
		//第三步:将gbk追加后的内容复制到utf-8中
//		cover(fOut, fIn);
	}
	
	//用一个文件覆盖另一个文件
	public static void cover(File from,File to){
		BufferedReader bufferedReader = null;
		BufferedWriter bufferedWriter = null;
		try {
			bufferedReader = new BufferedReader(
					new InputStreamReader(
							new FileInputStream(from),"gbk"));//在第二层声明转码格式
			bufferedWriter = new BufferedWriter(
					new OutputStreamWriter(
							new FileOutputStream(to),"utf-8"));
			
			String string = null;
			while((string = bufferedReader.readLine()) != null){
				//System.out.println(string);
				bufferedWriter.write(string);//返回的字符串不带换行符的
				bufferedWriter.newLine();//换行
			
				bufferedWriter.flush();//刷新缓冲区,将信息传入到指定文件中
			}	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			if(bufferedReader != null)
				try {
					bufferedReader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if(bufferedWriter != null)
				try {
					bufferedWriter.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}	
	}
	
	//在一个文件末尾追加内容
	public static void append(File file,String string){
		
		OutputStreamWriter outputStreamWriter = null;
		
		try {
			outputStreamWriter = new OutputStreamWriter(
					new FileOutputStream(file,true),"gbk");//在第一层内声明true,即在末尾追加
			outputStreamWriter.write(string + "\n");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			if(outputStreamWriter != null)
			try {
				outputStreamWriter.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	//将一个文件内容复制到另一个文件的内容
	public static void copy(File fIn,File fOut){
		BufferedReader bufferedReader = null;
		BufferedWriter bufferedWriter = null;
		try {
			bufferedReader = new BufferedReader(
					new InputStreamReader(
							new FileInputStream(fIn),"utf-8"));
			bufferedWriter = new BufferedWriter(
					new OutputStreamWriter(
							new FileOutputStream(fOut),"gbk"));
			
			String string = null;
			while((string = bufferedReader.readLine()) != null){
				System.out.println(string);
				bufferedWriter.write(string + "\n");	
				bufferedWriter.flush();
			}	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			if(bufferedReader != null)
				try {
					bufferedReader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if(bufferedWriter != null)
				try {
					bufferedWriter.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}
}
           

练习一:

package exercise;

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

/*
	练习:
		目的:复制一个图片
		思路:
			1、用字节读取流对象和图片相关联
			2、用字节写入流对象创建一个图片文件
			3、通过循环读写,完成数据的存储。
			4、关闭资源
 */
public class CopyPic {
	public static void main(String[] args) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		 
		try {
			fis = new FileInputStream("exercise/01.jpg");
			fos = new FileOutputStream("exercise/02.jpg");
			byte[] buf = new byte[1024];
			while(fis.read(buf) != -1){
				fos.write(buf,0,buf.length);
				fos.flush();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{	
			try {
				if (fis != null) 
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			try {
				if(fos != null)
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
           

练习二:

package exercise;

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

/*
	练习:
		复制MP3文件,通过缓冲区
		
 */
public class CopyMP3 {
	public static void main(String[] args) {
		//方式一:
		long start = System.currentTimeMillis();
		copy_1();
		long end = System.currentTimeMillis();
		System.out.println((end - start) + "毫秒");

	}
	
	//方式一:通过字节流的缓冲区完成复制
	public static void copy_1(){
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		 
		try {
			bis = new BufferedInputStream(new FileInputStream("exercise/01.mp3"));
			bos = new BufferedOutputStream(new FileOutputStream("exercise/02.mp3"));
			int len = 0;
			byte[] buf = new byte[1024];
			while((len = bis.read(buf)) != -1){
				//System.out.println(new String(buf));
				bos.write(buf,0,len);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				if(bis != null)
					bis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(bos != null)
					bos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}
}
           

继续阅读