缓冲流等
IO流:緩沖流等
回顧
1 File類 表示硬盤中一個文件或文件夾(目錄)文件: //1.1創建對象File file=new File("d:\\123.txt");//1.2判斷文件是否存在if(!file.exists()){file.createNewFile();}//1.3刪除file.delete();file.deleteOnExit();//退出jvm,刪除文件//1.4可執行、可讀、可寫file.canExecute();file.canRead();file.canWrite();//1.5獲取file.getAbsoulatePath();file.getPath();file.getName();file.getParent();file.lastModified();//修改時間//1.6判斷file.isFile();file.isHidden();file.renameTo();//重命名文件夾 ://2.1創建文件夾File dir=new File("d:\\aaa\\bbb");//2.2判斷是否存在if(!dir.exists()){dir.mkdir();//一級目錄dir.mkdirs();//多級目錄}//2.3刪除dir.delete();dir.deleteOnExit();//2.4獲取dir.getAbsoulatePath();dir.getPath();dir.getName();dir.getParent();//2.5判斷dir.isDirectory();dir.isHidden();dir.renameTo();//2.6列出來當前目錄下的文件和子文件夾dir.list();//String[]dir.listFiles();//File[]dir.list(FileNameFilter);File.listRoots();//返回所有的盤符2遍歷文件夾中所有的文件和子文件3遞歸刪除文件夾4 IO (Input Output)流:是數據傳輸的通道。輸入: 從外部存儲到內存(java程序)(讀取)輸出: 從內存到外部存儲 (寫入)IO分類 :1 按照流向 輸入流和輸出流2 按照字節個數 字節流和字符流3 按照功能 節點流和處理流5 字節流 InputStream ----> FileInputStreamOutputStream ---->FileOutputStream6 字符流Reader ----->InputStreamReader---->FileReaderWriter ----->OutputStreamWriter---->FileWriter7 復制文件使用字節流復制今天內容
1.轉換流1.1 InputStreamReader類的使用1.2 OutputStreamWriter類的使用 2.緩沖流2.1 BufferedInputStream類的使用2.2 BufferedOutputStream類的使用2.3 BufferedReader類的使用2.4 BufferedWriter類的使用 3.內存流 4.標準輸入輸出流 5.對象流 6.RandomAccessFile類 7.Properties類 8.裝飾者設計模式教學目標
1.掌握轉換流的使用 2.掌握緩沖流的使用 3.了解內存流的使用 4.了解標準輸入輸出流的使用 5.掌握對象流的使用 6.了解RandomAccessFile類的使用 7.了解Properties的使用 8.了解裝飾者設計模式第一節 轉換流
作用:a.實現字節流到字符流的轉換b.解決中文亂碼的問題中文編碼gb2312 (采用兩個字節保存字符漢字,英文數字一個字節)GBK (采用兩個字節保存字符漢字,英文數字一個字節)GB18030 (英文數字都是一個字節,中文是兩個或四個字節)Unicode字符集(包含每個國家的所有字符)國際通用unicode編碼 使用兩個字節---65536個字符,浪費空間為了節省空間使用轉碼形式utf-8 使用 1 、2、3個字節 (EF BB BF 記事本添加的BOM(Byte Order Mark)頭,編碼的標記)utf-16 使用兩個字節---65536個字符 (FF FE 小端(尾) FE FF 大端(尾))utf-32 使用4個字節臺灣 big5ANSI:在簡體中文Windows操作系統中, ANSI 編碼代表 GBK 編碼只有轉換流才能指定讀取和寫入的字符集1.1 InputStreamReader類
InputStreamReader:字節字符轉換輸入流,將字節輸入流轉換為字符輸入流代碼實現:
public class InputStreamReaderDemo {public static void main(String[] args) throws IOException {//1.實例化File的對象//File file = new File("file/input1.txt");//2.實例化轉換輸入流的對象//注意:當一個流的存在的意義是為了實例化另外一個流,則這個流不需要手動進行關閉//InputStream input = new FileInputStream(file);//InputStreamReader reader = new InputStreamReader(input);//使用默認的字符集【GBK】進行實例化轉換流//InputStreamReader reader = new InputStreamReader(new FileInputStream(new File("file/input1.txt")));//使用指定字符集進行實例化轉換流//字符集一般使用字符串直接傳參,不區分大小寫,但是,如果字符集書寫有誤的話,則會跑出java.io.UnsupportedEncodingExceptionInputStreamReader reader = new InputStreamReader(new FileInputStream(new File("file/input1.txt")),"UTF-8");//3.讀取char[] arr = new char[16];int len = 0;while((len = reader.read(arr)) != -1) {String string = new String(arr, 0, len);System.out.println(string);}reader.close();} }1.2 OutputStreamWriter類
OutputStreamWriter:字符轉換輸出流,將內存中的字符轉成字節保存到硬盤中。代碼實現:
public class OutputStreamWriterDemo {public static void main(String[] args) throws IOException {//需求:將一段文本以utf-8的格式寫入到文件中【注,文件格式為默認格式】//1.實例化FIle對象//注意:對于所有的輸出流而言,文件可以不存在,在進行寫入的過程中可以自動進行創建//但是,對于所有的輸入流而言,文件必須先存在,然后才能操作,否則,會拋出FileNotFounedExceptionFile file = new File("file/output1.txt");//2.實例化轉換輸出流//如果不想覆蓋源文件中的內容時,則在傳參的時候,設置一個參數為trueOutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file,true), "utf-8");//3.寫入writer.write("家客戶放假啊剛回家");//4.刷新writer.flush();//5.關閉writer.close();} }第二節 緩沖流
作用:主要是為了增強基礎流的功能而存在的,提高了流的工作效率【讀寫效率】注意:如果使用記事本創建的文件,文件是utf-8或者unicode編碼,文件的前面有一個BOM(Byte Order Mark)頭,BOM作用指定文件使用的編碼類型。GBK編碼沒有添加bom頭。 utf-8:EF BB BF unicode 小端: FF FE 66 00 unicode 大端 :FE FF 00 662.1 BufferedInputStream類
public class BufferedInputStreamDemo {public static void main(String[] args) throws IOException {//實例化一個File對象File file = new File("file/test22.txt");//實例化一個緩沖字節輸入流的對象BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));/*//讀取byte[] arr = new byte[1024];int len = 0;while((len = input.read(arr)) != -1) {String string = new String(arr, 0, len);}*/byte[] arr = new byte[4];int len = input.read(arr);String string = new String(arr, 0, len);System.out.println(string);input.mark(66);len = input.read(arr);string = new String(arr, 0, len);System.out.println(string);// 實現了效果:覆水可收input.reset();len = input.read(arr);string = new String(arr, 0, len);System.out.println(string);input.close();} }2.2 BufferedOutputStream類
public class BufferedOutputStreamDemo {public static void main(String[] args) throws IOException {//實例化FIle對象File file = new File("test33.txt");//實例化換種字節輸出流 BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));//寫output.write("你好的halle".getBytes());//刷新output.flush();//關閉output.close();} }2.3 BufferedReader類
public class BufferedReaderDemo {public static void main(String[] args) throws IOException {//實例化FIle對象File file = new File("test33.txt");//實例化緩沖字符流的對象BufferedReader reader = new BufferedReader(new FileReader(file));//方式一:read循環讀取/*//讀取char[] arr = new char[8];int len = 0;while((len = reader.read(arr)) != -1) {String string = new String(arr, 0, len);}*///方式二:readLine循環讀取/*String result1 = reader.readLine();System.out.println(result1);String result2 = reader.readLine();System.out.println(result2);*/String result = "";while((result = reader.readLine()) != null) {System.out.println("第一行:" + result);}reader.close();} }2.4 BufferedWriter類
public class BufferedWriterDemo {public static void main(String[] args) throws IOException {// 實例化FIle對象File file = new File("test33.txt");//實例化緩沖字符輸出流BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));// 寫writer.write("今天天氣還可以");// 作用:主要就是為了換行writer.newLine();// 刷新writer.flush();//關閉writer.close();} }第三節 內存流
輸入和輸出都是從文件中來的,當然,也可將輸出輸入的位置設置在內存上,這就需要ByteArrayInputStream和ByteArrayOutputStreamByteArrayInputStream:將內容寫入到內存中,是Inputstream的子類ByteArrayOutputStream:將內存中數據輸出,是OutputStream的子類此時的操作應該以內存為操作點案例:完成一個字母大小寫轉換的程序
public class TextDemo02 {public static void main(String[] args) throws IOException {//定義一個字符串,全部由大寫字母組成String string = "HELLOWORLD";//內存輸入流//向內存中輸出內容,注意:跟文件讀取不一樣,不設置文件路徑ByteArrayInputStream bis = new ByteArrayInputStream(string.getBytes());//內存輸出流//準備從內存中讀取內容,注意:跟文件讀取不一樣,不設置文件路徑ByteArrayOutputStream bos = new ByteArrayOutputStream();int temp = 0;//read()方法每次只讀取一個字符while((temp = bis.read()) != -1) {//將讀取的數字轉為字符char c = (char)temp;//將字符變為大寫bos.write(Character.toLowerCase(c));}//循環結束之后,所有的數據都在ByteArrayOutputStream中//取出內容,將緩沖區內容轉換為字符串String newString = bos.toString();//關閉流bis.close();bos.close();System.out.println(newString);} } 注意:內存操作流的操作對象,一定是以內存為主準,不要以硬盤為準。第四節 標準輸入輸出流
Java的標準輸入/輸出分別通過System.in和System.out實現,默認情況下分別代表是鍵盤和顯示器PrintStream類:PrintStream為其他輸出流添加了功能,使它們能夠方便地打印各種數據值表示形式。
PrintWriter類:向文本輸出流打印對象的格式化表示形式。此類實現在 PrintStream中的所有 print方法。它不包含用于寫入原始字節的方法。
public static void main(String[] args)throws Exception {//1創建PrintStream//PrintStream ps=new PrintStream("d:\\print.txt");PrintWriter pw=new PrintWriter("d:\\print.txt");//2打印pw.println(true);pw.println(3.14);pw.println(100);pw.println("我愛北京");//3刷新pw.flush();//4關閉pw.close();} public class PrintStreamDemo {public static void main(String[] args) throws FileNotFoundException {//System.out.println("hello world");//創建打印流的對象//注意:默認打印到控制臺,但是,如果采用setOut方法進行重定向之后,將輸出到指定的文件中PrintStream print = new PrintStream(new FileOutputStream(new File("test33.txt")));/** static void setErr(PrintStream err) 重新分配“標準”錯誤輸出流。 static void setIn(InputStream in) 重新分配“標準”輸入流。 static void setOut(PrintStream out) 重新分配“標準”輸出流。 * *///將標準輸出重定向到print的輸出流System.setOut(print);System.out.println("hello world");} } public class InputStreamDemo {public static void main(String[] args) throws FileNotFoundException {FileInputStream inputStream = new FileInputStream(new File("test33.txt"));//setInSystem.setIn(inputStream);//System.out.println("請輸入內容:");//默認情況下是從控制臺進行獲取內容//但是如果使用setIn方法設置了重定向之后,將從指定文件中獲取內容Scanner sc = new Scanner(System.in);String string = sc.next();System.out.println(string);} }第五節 對象流
流中流動的數據是對象將一個對象寫入到本地文件中,被稱為對象的序列化將一個本地文件中的對象讀取出來,被稱為對象的反序列化 使用對象流ObjectInputStream: 對象輸出流ObjectOutputStream:對象輸入流注意:序列化對象的類型必須實現Serializable接口。否則不能序列化。如果向將多個對象序列化到本地,可以借助于集合,【思路:將多個對象添加到集合中,將集合的對象寫入到本地文件中,再次讀出來,獲取到的仍然是集合對象,遍歷集合】。 對象中那些字段可以不序列化:1 transient 修飾的字段2 靜態的字段 在要序列化類中添加字段,保證序列化和反序列化是同一個類 private static final long serialVersionUID = 100L; public class ObjectStreamDemo {public static void main(String[] args) {// TODO Auto-generated method stub//objectOutputStreamUsage();objectInputStreamUsage();}// 寫:將對象進行序列化public static void objectOutputStreamUsage() {//1.實例化一個Person的對象Person person = new Person("張三", 10, 'B');//2.實例化一個對象輸出流的對象ObjectOutputStream output = null;try {output = new ObjectOutputStream(new FileOutputStream(new File("file/person.txt")));//3.將對象寫入到流中output.writeObject(person);//4.刷新output.flush();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {output.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}// 讀:反序列化public static void objectInputStreamUsage() {//1.實例化對象輸入流的對象try {ObjectInputStream input = new ObjectInputStream(new FileInputStream(new File("file/person.txt")));//2.讀取Object object = input.readObject();//3.對象的向下轉型if(object instanceof Person) {Person p = (Person)object;System.out.println(p);}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}} } 注意:在使用對象流的時候,用于初始化對象流的參數只能是字節流(將對象轉換為二進制的形式,然后再把二進制寫入文件)第六節 RandomAccessFile類
RandomAccessFile是用來訪問那些保存數據記錄的文件的,你就可以用seek( )方法來訪問記錄,并進行讀寫了。這些記錄的大小不必相同;但是其大小和位置必須是可知的。但是該類僅限于操作文件。案例一:RandomAccessFile類的應用
public class TextDemo01 {public static void main(String[] args) throws Exception {RandomAccessFile file = new RandomAccessFile("file.txt", "rw");// 以下向file文件中寫數據file.writeInt(20);// 占4個字節file.writeDouble(8.236598);// 占8個字節//這個長度寫在當前文件指針的前兩個字節處,可用readShort()讀取file.writeUTF("這是一個UTF字符串");file.writeBoolean(true);// 占1個字節file.writeShort(395);// 占2個字節file.writeLong(2325451l);// 占8個字節file.writeUTF("又是一個UTF字符串");file.writeFloat(35.5f);// 占4個字節file.writeChar('a');// 占2個字節//把文件指針位置設置到文件起始處file.seek(0);// 以下從file文件中讀數據,要注意文件指針的位置System.out.println("——————從file文件指定位置讀數據——————");System.out.println(file.readInt());System.out.println(file.readDouble());System.out.println(file.readUTF());//將文件指針跳過3個字節,本例中即跳過了一個boolean值和short值。file.skipBytes(3);System.out.println(file.readLong());//跳過文件中“又是一個UTF字符串”所占字節//注意readShort()方法會移動文件指針,所以不用寫2。file.skipBytes(file.readShort()); System.out.println(file.readFloat());// 以下演示文件復制操作System.out.println("——————文件復制(從file到fileCopy)——————");file.seek(0);RandomAccessFile fileCopy = new RandomAccessFile("fileCopy.txt", "rw");int len = (int) file.length();// 取得文件長度(字節數)byte[] b = new byte[len];//全部讀取file.readFully(b);fileCopy.write(b);System.out.println("復制完成!");} }第七節 Properties類
是Map接口的一個實現類,并且是Hashtable的子類Properties集合中元素也是以鍵值對的形式存在的Properties特點: 1 存儲屬性名和屬性值 2 屬性名和屬性值都是字符串 3 和流有關系 4 沒有泛型 public class PropertiesDemo {public static void main(String[] args) {//1.實例化一個Properties的對象Properties pro = new Properties();System.out.println(pro);//2.把文件userlist.properties中的鍵值對同步到集合中//實質:讀取/*** void load(InputStream inStream) 從輸入流中讀取屬性列表(鍵和元素對)。 */try {pro.load(new BufferedInputStream(new FileInputStream(new File("file/userlist.properties"))));} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(pro);//3.向集合中添加一對鍵值對/** Object setProperty(String key, String value) 調用 Hashtable 的方法 put。 * */pro.setProperty("address", "china");System.out.println(pro);try {//4.store//實質:寫入//comments:工作日志pro.store(new BufferedOutputStream(new FileOutputStream(new File("file/userlist.properties"))), "add a pair of key and value");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} }第八節 裝飾者設計模式
裝飾模式指的是在不必改變原類文件和繼承的情況下,動態地擴展一個對象的功能。它是通過創建一個包裝對象,也就是裝飾來包裹真實的對象。應用場景:需要擴展一個類的功能,或給一個類添加附加職責。 案例:1 抽象類 ReadFile -->read抽象方法 2 定義一些子類ReadTextFile 讀取文本文件ReadMusicFile 讀取音樂文件ReadVideoFile 讀取視頻文件 3 要求:提高三個類的功能:帶緩沖 3.1繼承BufferedReadTextFile繼承ReadTextFile 重寫 read方法BufferedReadMusicFile繼承ReadMusicFile 重寫 readBufferedReadVideoFile繼承ReadVideoFile 重寫 read缺點:1 類體系太龐大 2 耦合性太高3.2裝飾者設計模式 :采用組合的關系BufferedReadFile{private ReadFile readFile;public BufferedReadFile(ReadFile readFile){this.readFile=readFile;}public void read(){///}}優點:耦合性低,提高重用性代碼實現:
/*** 抽象人類* @author wgy**/ public abstract class AbstractPerson {public abstract void eat(); } /** *子類1 */ public class Person extends AbstractPerson {String name;public void eat() {System.out.println(name+"正在吃東西.........");}} package com.qf.day18_6; /*** 子類2* @author wgy**/ public class Person2 extends AbstractPerson{String name;@Overridepublic void eat() {System.out.println(name+"吃......");}} package com.qf.day18_6;import java.io.BufferedInputStream;/*** 增強Person* @author wgy**/ public class StrongPerson extends AbstractPerson {//使用person創建一個變量AbstractPerson p;public StrongPerson(AbstractPerson p) {this.p = p;}public void eat() {p.eat();System.out.println("抽一口");System.out.println("瞇一會");System.out.println("寫會java代碼");}} //測試類 package com.qf.day18_6;public class Test {public static void main(String[] args) {Person benwei=new Person();benwei.name="本偉";Person2 zhengshuai=new Person2();zhengshuai.name="鄭帥";StrongPerson strongPerson=new StrongPerson(benwei);StrongPerson strongPerson2=new StrongPerson(zhengshuai);strongPerson.eat();strongPerson2.eat();} }總結
轉換流 緩沖流 內存流 標準輸入輸出輪流 對象流 RandomAccessFile類 Properties 裝飾者設計模式默寫
1.使用轉換流實現文件內容的拷貝2.使用字符緩沖流實現文件內容的拷貝作業
1.在電腦中盤下創建一個文件為HelloWorld.txt文件,判斷他是文件還是目錄,在創建一個目 錄FileTest,之后將HelloWorld.txt移動到FileText目錄下去 2.在程序中寫一個"HelloJavaWorld你好世界"輸出到操作系統文件Hello.txt文件中 3.從磁盤讀取一個文件到內存中,再打印到控制臺 4.統計一個含有英文單詞的文本文件的單詞個數 5.從磁盤讀取一個文件到內存中,再打印到控制臺 6.實現將一個文件夾中的一張圖片拷貝到另外一個文件夾下 7.將上課關于不同的流實現拷貝的案例敲熟練 8.定義一個類Student,定義屬性:學號、姓名和成績,方法:show(顯示個人信息)實例化幾個Student對象,將這幾個對象保存到student.txt文件中然后再將文件中的內容讀取出來并且調用show方法9.從控制臺輸入一個字符串,統計其中一個字符出現的次數 10.理解裝飾者設計模式,并實現類似課堂案例的案例面試題
1.BufferedReader屬于哪種流,它主要是用來做什么的,它里面有那些經典的方法 2.怎么樣把輸出字節流轉換成輸出字符流,說出它的步驟 3.流一般需要不需要關閉,如果關閉的話在用什么方法,一般要在那個代碼塊里面關閉比較好,處理流是怎么關閉的,如果有多個流互相調用傳入是怎么關閉的? 4.什么叫對象序列化,什么是反序列化,實現對象序列化需要做哪些工作 5.在實現序列化接口是時候一般要生成一個serialVersionUID字段,它叫做什么,一般有什么用 6.什么是內存流?有什么作用轉載于:https://www.cnblogs.com/Zzzxb/p/11397148.html
總結
- 上一篇: 学生信息管理系统报告
- 下一篇: document操作自定义属性