天天看點

Java學習路程之位元組流和字元流

一.位元組流

1.特點:位元組流可以将文字、圖檔、音頻等檔案類型轉換成位元組進行資料的傳輸。

2.分類:

輸入流 InPutStream

輸出流 OutPutStream

判斷參照物(程式)來判斷是輸入流還是輸出流,OutPutStream和InPutStream是所有位元組流的父類

3.區分:

從程式到檔案是輸出流 寫檔案

(1). 建立位元組輸出流:

public class Day19 {
	public static void main(String[] args) throws IOException {
		//建立位元組輸出流
		FileOutputStream fos = new FileOutputStream("/Users/lanou/Desktop/test/haha.txt");
		//寫入方法write(),該方法是按照ASCII碼寫入檔案,在haha.txt檔案中寫入了A B.
		fos.write(65);
		fos.write(66);
		//關閉資源
		//fos.close();
		//利用位元組數組寫入
		byte[] b = {65,66,67};
		fos.write(b);//在haha.txt檔案中寫入了A B C
		//按偏移量寫入位元組數組
		fos.write(b, 0, 2);//在haha.txt檔案中寫入了A B
		//hello轉成字元數組寫入
		fos.write("hello".getBytes());//在haha.txt檔案中寫入了hello
	}
}
           

帶異常處理的寫入:

public class Demo01 {
	public static void main(String[] args)  {
		//帶異常處理的寫入
		FileOutputStream fos = null;
		try {
		    fos = new FileOutputStream("/Users/lanou/Desktop/test/haha.txt");
			//寫檔案
		    fos.write(65);
		} catch (FileNotFoundException e) {
			throw new RuntimeException("沒有該檔案");
		} catch (IOException e) {
			throw new RuntimeException("寫入失敗");
		}finally {
			//不能直接關閉資源,因為fos的初始值為null,當寫入失敗時,null不能調用方法
			if (fos != null) {
				try {
					//不管報不報異常都要将流關閉
					fos.close();
				} catch (Exception e2) {
					throw new RuntimeException("關閉失敗");
				}
			}
		}
		
	}
           

(2).檔案的讀取

public class Day19 {
	public static void main(String[] args) throws IOException {
		
		FileInputStream fis = new FileInputStream("/Users/lanou/Desktop/test/haha.txt");
		//讀取檔案
		fis.read();//單個讀取檔案
		//循環讀取檔案
		int num= 0;
		while ((num = fis.read()) != -1) {
			System.out.println(num);//haha.txt中的内容全部讀取出來
		}
		fis.close();
		//位元組數組讀取
		//建立數組
		byte[] b = new byte[1024];//數組長度一般填1024或1024的整數倍
		int len = 0;
		while ((len = fis.read(b)) != -1) {
			System.out.println(new String(b, 0, len));//haha.txt中的内容全部讀取出來
		}
	}
}
           

練習1:

複制檔案 ,計算兩種讀取檔案的時間, 帶異常處理

單個讀取:

public static void main(String[] args) {
		
		//計算時間
		long start = System.currentTimeMillis();//開始時間
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("/Users/lanou/Desktop/test/java入門.pptx");
			fos = new FileOutputStream("/Users/lanou/Desktop/test/java.pptx");
			int num = 0;
			while ((num = fis.read()) != -1) {
				//寫入檔案
				fos.write(num);
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("沒有此檔案");
		}catch (IOException e) {
			throw new RuntimeException("讀寫失敗");
		}finally {
			if (fos != null) {
				try {
					fos.close();//關閉資源
				} catch (Exception e2) {
					throw new RuntimeException("關閉失敗");
				}finally {
					if (fis != null) {
						try {
							fis.close();
						} catch (Exception e3) {
							throw new RuntimeException("關閉失敗");
						}
					}
				}
			}
		}
		
		long end = System.currentTimeMillis();//結束時間
		System.out.println((end - start)/1000 + "秒");
	}

位元組數組讀取:
public static void main(String[] args) {
		//計算時間
		long start = System.currentTimeMillis();//開始時間
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("/Users/lanou/Desktop/test/java入門.pptx");
			fos = new FileOutputStream("/Users/lanou/Desktop/test/java.pptx");
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = fis.read(b)) != -1) {
				fos.write(b, 0, len);
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("沒有此檔案");
		}catch (IOException e) {
			throw new RuntimeException("讀寫失敗");
		}finally {
			if (fos != null) {
				try {
					fos.close();//關閉資源
				} catch (Exception e2) {
					throw new RuntimeException("關閉失敗");
				}finally {
					if (fis != null) {
						try {
							fis.close();
						} catch (Exception e3) {
							throw new RuntimeException("關閉失敗");
						}
					}
				}
			}
		}
		
		long end = System.currentTimeMillis();//結束時間
		System.out.println((end - start)/1000 + "秒");
	}
           

練習2:

将一個檔案夾 複制 到另一個檔案夾下

public static void main(String[] args) throws IOException {
		//将一個檔案夾 複制 到另一個檔案夾下
		File src = new File("/Users/lanou/Desktop/test");
		File desc = new File("/Users/lanou/Desktop/heihei");
		copyDir(src, desc);
	}
	//将一個檔案夾 複制 到另一個檔案夾下
	//src 源檔案   desc 目标檔案
 	public static void copyDir(File src,File desc) throws IOException {
 		//在目标檔案夾下建立檔案夾
		File newFile = new File(desc, src.getName());
		newFile.mkdir();
		File[] listFiles = src.listFiles();
		for (File subFile : listFiles) {
			if (subFile.isFile()) {
				//是檔案進行讀寫
				FileInputStream fis = new FileInputStream(subFile);
				File file = new File(newFile, subFile.getName());
				//寫入
				FileOutputStream fos = new FileOutputStream(file);
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = fis.read(b)) != -1) {
					fos.write(b, 0, len);
				}
				fis.close();
				fos.close();
			}else {
				//不是檔案繼續周遊
				copyDir(subFile, newFile);
			}
		}
	}
           

練習3:

将一個檔案夾下的所有txt檔案 複制到,另一個檔案夾下并且儲存為.java檔案

public static void copyTxtFile(File src, File desc) throws IOException {
		File[] listFiles = src.listFiles(new GetTxtFile());
		for (File subFile : listFiles) {
			if (subFile.isFile()) {
				FileInputStream fis = new FileInputStream(subFile);
				//是檔案,進行分割擷取檔案名
				String name = subFile.getName();//擷取源TXT檔案名
				String[] split = name.split("\\.");
				//輸出流路徑名
				File file = new File(desc, split[0] + ".java");
				//建立輸出流
				FileOutputStream fos = new FileOutputStream(file);
				byte[] b = new byte[1024]; 
				int len = 0;
				while ((len = fis.read()) != -1) {
					fos.write(b, 0, len);
				}
				fis.close();
				fos.close();
			}else {
				//檔案夾
				copyTxtFile(subFile, desc);
			}
		}

//建立過濾器,找到是txt檔案
class GetTxtFile implements FileFilter{
	public boolean accept(File pathname) {
		if (pathname.isDirectory()) {
			return true;
		}
		return pathname.getName().endsWith("txt");
	}
}
           

二.字元流

1.分類

Writer 寫入

Reader 讀取

是所有字元流的父類

public class Day19 {
	public static void main(String[] args) {
		//建立字元輸出流
		FileWriter fw = new FileWriter("/Users/lanou/Desktop/test/cs.txt");
		//寫入檔案
		fw.write(65);//cs.txt檔案寫入A
		//重新整理,為了内容真正寫入檔案
		fw.flush();
		//字元數組寫入
		char[] c = {'1','2','3'};
		fw.write(c);
		fw.flush();
		//關閉前系統會自動重新整理
		/字元串直接寫入
		fw.write("真正的勇士,敢于直面慘淡的人生" +"\n" + "敢于正視淋漓的鮮血");
		fw.close();
		
		//建立輸入流
		FileReader fReader = new FileReader("/Users/lanou/Desktop/test/cs.txt");
		//單個讀
		int num = 0;
		while ((num = fReader.read()) != -1) {
			System.out.print((char)num);
		}
		//數組讀取
		char[] c = new char[1024];
		int len = 0;
		while ((len = fReader.read(c)) != -1) {
			System.out.println(new String(c, 0, len));
		}
	}
}
           

練習:

複制文本檔案,使用字元流,帶異常處理

public class Day19 {
	public static void main(String[] args) {
		FileWriter fWriter = null;
		FileReader fReader = null;
		try {
			fReader = new FileReader("/Users/lanou/Desktop/test/cs.txt");
			fWriter = new FileWriter("/Users/lanou/Desktop/heihei/cs.txt");
			//建立字元數組
			char[] chars = new char[1024];
			int len = 0;
			//循環讀取寫入
			while ((len = fReader.read(chars)) != -1) {
				fWriter.write(chars, 0, len);
				fWriter.flush();//重新整理
			}
			
		} catch (FileNotFoundException e) {
			throw new RuntimeException("沒找到檔案");
		}catch (Exception e) {
			throw new RuntimeException("讀寫失敗");
		}finally {
			//關閉fReader
			if (fReader != null) {
				try {
					fReader.close();
				} catch (Exception e2) {
					throw new RuntimeException("關閉失敗");
				}finally {
					//關閉fWriter
					if (fWriter != null) {
						try {
							fWriter.close();
						} catch (Exception e3) {
							throw new RuntimeException("關閉失敗");
						}
					}
				}
			}
		}
	}
}