天天看點

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();
			}
		}	
	}
}
           

繼續閱讀