Java-----关于IO流的总结
流的分類: 因為分類的方式不同,可以將流分為不同的類型:
(1)按照流向:分為 **輸入流** 和 **輸出流**。輸入流:表示將數據讀取到java程序(內存)中使用的流。 輸出流:表示從java程序(內存)向外傳輸使用的流。 (2)按照讀取的數據單元: 分為 **字節流** 和 **字符流**字節流 :一次性傳輸一個字節數據,將數據以字節的形式傳輸。字符流: 一次性傳輸一個字符(1、2或3個字節)數據,將數據以字符的形式傳輸。 (3)按照流的角色: 分為: **節點流** 和 **處理流**節點流:可以從或向一個特定的地方(節點)讀寫字節數據。處理流:是對一個已存在的流的連接和封裝,通過所封裝的流的功能調用實現數據讀寫。結構圖
輸入輸出流
1 字節輸入流: InputStream類的常用方法
InputStream是一個抽象類,不能實例化對象。| void close() | 關閉此輸入流并釋放與該流關聯的所有系統資源。 |
| int read() | 從輸入流中讀取數據的下一個字節。 |
| int read(byte[] b) | 從輸入流中讀取一定數量的字節,并將其存儲在緩沖區數組b中。 |
| int read(byte[] b,int off, int len) | 將輸入流中最多len個數據字節讀入 byte 數組。 |
2 字節輸出流:OutputStream類的常用方法
OutputStream是抽象類,不能實例化對象。| void close() | 關閉此輸出流并釋放與此流有關的所有系統資源。 |
| void flush() | 刷新此輸出流并強制寫出所有緩沖的輸出字節。 |
| void write(byte[] b) | 將 b.length 個字節從指定的 byte 數組寫入此輸出流。 |
| void write(byte[] b,int off, int len) | 將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此輸出流。 |
| void write(int b) | 將指定的字節寫入此輸出流 |
(1) 文件輸入流FileInputStream
public class DemoFileInputStream { public static void main(String[] args) { //創建被操作文件:此文件必須存在,否則讀取時,拋出文件找不到異常 File file = new File("test\\hello.txt"); //聲明流,不初始化 FileInputStream fis = null; try {//初始化流fis = new FileInputStream(file);//準備數組用來存儲數據byte[] b = new byte[3]; //先定義一個變量,初始值是‐1int i = ‐1; //定義一個計數循環的變量int count = 0; //while循環讀取while((i=fis.read(b))!=‐1) {count++; for(int j=0; j<i; j++) {System.out.print((char)b[j]);}}System.out.println(count);//計數:計算循環讀取的次數} catch (FileNotFoundException e) { // TODO Auto‐generated catch block e.printStackTrace(); }catch (IOException e) {// TODO Auto‐generated catch block e.printStackTrace(); }finally {if(fis!=null) {try {fis.close();} catch (IOException e) {// TODO Auto‐generated catch block e.printStackTrace();}}}}}(2)文件輸出流FileOutputStream
public class TestFileOutputStream {public static void main(String[] args) {//向文件中寫入數據 //在工程中創建一個test文件夾 //設計程序,向test\\hello.txt中寫入hello world//第一步:創建被操作文件對象//當向一個文件中寫入數據時,若文件不存在,程序會自動創建File file = new File("test\\hello.txt"); FileOutputStream fos = null; try {//第二步:創建流對象 fos = new FileOutputStream(file, true);//第三步:準備數據 String str = "hello world";byte[] b = str.getBytes();System.out.println(b.length); //第四步:使用流寫入fos.write(b);}catch(IOException e) {e.printStackTrace();} finally { if(fos!=null) {try {//第五步:刷新流,關閉流fos.flush();fos.close();} catch (IOException e) { // TODO Auto‐generated catch block e.printStackTrace();}} }} }1 字符輸入流
Reader類 Reader:是所有字符輸入流的父類,為一個抽象類,不能實例化對象,使用它的子類FileReader類
2 字符輸出流
Writer類 Writer:是所有字符輸出流的父類,為一個抽象類,不能實例化對象,使用它的子類FileWriter類
轉換流
作用: 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 編碼只有轉換流才能指定讀取和寫入的字符集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(); } }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(ByteOrder Mark)頭,BOM作用指定文件使用的編碼類型 GBK編碼沒有添加bom頭。 utf-8:EF BB BF unicode 小端: FF FE 66 00 unicode 大端 :FE FF 00 661 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 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(); } }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(); } }4 BufferedWriter類
public class BufferedWriterDemo {
public static void main(String[] args) throws IOException {
// 實例化FIle對象
File file = new File(“test33.txt”);
內存流
輸入和輸出都是從文件中來的,當然,也可將輸出輸入的位置設置在內存上,這就需要ByteArrayInputStream和 ByteArrayOutputStream
ByteArrayInputStream:將內容寫入到內存中,是Inputstream的子類 ByteArrayOutputStream:將內存中數據輸出,是OutputStream的子類此時的操作應該以內存為操作點構造方法及常用方法
ByteArrayInputStream
ByteArrayOutputStream
構造方法及常用方法
ByteArrayOutputStream() 創建一個新的字節數組輸出流。 ByteArrayOutputStream(int size) 創建一個新的字節數組輸出流,具有指定大小的緩沖區容量(以字節為單位)。 void close() ; 關閉 ByteArrayOutputStream沒有任何效果。 void reset() ; 將此字節數組輸出流的 count字段重置為零,以便丟棄輸出流中當前累積的所有輸出。 int size() ; 返回緩沖區的當前大小。 byte[] toByteArray() ; 創建一個新分配的字節數組。 String toString(); 使用平臺的默認字符集將緩沖區內容轉換為字符串解碼字節。 (將內容從內存輸出到控制臺常用的兩個)void write(byte[] b, int off, int len); 從指定的字節數組寫入 len字節,從偏移量為 off開始,輸出到這個字節數組輸出流。 void write(int b) ;將指定的字節寫入此字節數組輸出流。 void writeTo(OutputStream out) ;將此字節數組輸出流的完整內容寫入指定的輸出流參數,就像使用 out.write(buf, 0, count); 調用輸出流的寫入方法 out.write(buf, 0, count) 。使用內存流讀寫數據和完成大小寫轉換
ackage com.qf.day18;import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream;/*** 使用內存流讀寫數據* * @author wgy**/ public class Demo6 {public static void main(String[] args) throws Exception{//read();//write();String s=toUpperCase("hello");System.out.println(s);}public static void read() throws Exception{String s="helloworld";//數據源byte[] data=s.getBytes();//1創建流ByteArrayInputStream bais=new ByteArrayInputStream(data);//2讀取int d=-1;while((d=bais.read())!=-1) {System.out.print((char)d);}//3關閉bais.close();}public static void write() throws Exception{//1創建內存流ByteArrayOutputStream baos=new ByteArrayOutputStream();//內部維護一個保存數據的數組//2寫入baos.write(97);baos.write(98);baos.write(99);//3關閉baos.close();String data=baos.toString(); //獲取寫到內存中的數據 // 或 byte [] a =baos.toByteArray();System.out.println(data);}//使用內存流實現小寫轉成大寫字母public static String toUpperCase(String str) throws Exception{byte[] bs=str.getBytes();//1創建內存流ByteArrayInputStream bais=new ByteArrayInputStream(bs);ByteArrayOutputStream baos=new ByteArrayOutputStream();int d=-1;//2讀寫while((d=bais.read())!=-1) {char c=(char)d;char c2=Character.toUpperCase(c);baos.write(c2);}//3關閉bais.close();baos.close();return baos.toString(); }}注意:內存操作流的操作對象,一定是以內存為主準,不要以硬盤為準 。
標準輸入輸出流
Java的標準輸入/輸出分別通過System.in和System.out實現,默認情況下分別代表是鍵盤和顯示器
PrintStream類:PrintStream為其他輸出流添加了功能,使它們能夠方便地打印各種數據值表示形式。
一些常用方法:
PrintStream append(char c) 將指定的字符附加到此輸出流。 PrintStream append(CharSequence csq) 將指定的字符序列附加到此輸出流。 PrintStream append(CharSequence csq, int start, int end) 將指定字符序列的子序列附加到此輸出流。 void print(boolean b) 打印布爾值。 void print(char c) 打印一個字符 void print(char[] s) 打印字符數組。 void print(double d) 打印雙精度浮點數。 void print(float f) 打印浮點數。 void print(int i) 打印一個整數。 void print(long l) 打印一個長整數。 void print(Object obj) 打印一個對象。 void print(String s) 打印字符串。 PrintStream printf(Locale l, String format, Object... args) 使用指定的格式字符串和參數將格式化的字符串寫入此輸出流的便利方法。 PrintStream printf(String format, Object... args) 使用指定的格式字符串和參數將格式化的字符串寫入此輸出流的便利方法。 void println() 通過寫入行分隔符字符串來終止當前行。 void println(boolean x) 打印一個布爾值,然后終止該行。 void println(char x) 打印一個字符,然后終止該行。 void println(char[] x) 打印一個字符數組,然后終止該行。 void println(double x) 打印一次,然后終止行。 void println(float x) 打印一個浮點數,然后終止該行。 void println(int x) 打印一個整數,然后終止行。 void println(long x) 打印很長時間,然后終止行。 void println(Object x) 打印一個對象,然后終止該行。 void println(String x) 打印一個字符串,然后終止行。 void write(byte[] buf, int off, int len) 從指定的字節數組寫入 len個字節,從偏移 off開始到此流。 void write(int b) 將指定的字節寫入此流。重定向:
System類里的方法:
static void setErr(PrintStream err); 重定向“標準” 錯誤輸出流。 static void setIn(InputStream in); 重定向“標準” 輸入流。 static void setOut(): 重定向“標準” 輸出流;重定向到文件輸出:
public class ReadirectOut{public static void main(String [] args){try{PrintStream psi = new PrintStream(new FileOutputStream("out.txt"));System.out.setOut(psi);System.out.println("本應輸出到控制臺的字符串和整型3:"+3);System.out.println("輸出對象:"+new ReadirectOut);}catch(IOException ex){ex.printStackTrce();} }重定向到標準輸入:
public class ReadirectIn{public static void main(String [] args){try{FileInputStream sis = new FIleInputStream("ReadirectIn.java");System.setIn(fis);//使用System.in 創建Scanner對象,用于獲取標準輸入Scanner sc = new Scanner(System.in);//增加下面一行 只把回車作為換行符sc.useDelimiter("\n");while(sc.hasNext){System.out.println("鍵盤輸入的內容是:"+sc.next);}}catch(IOexception s){s.printStackTrace();}} }從控制臺讀取數據
public class Demo8 {public static void main(String[] args)throws Exception {InputStream is = System.in;//2讀取數據int d1 = is.read();System.out.println((char)d1); // 不可輸入漢字int d =-1;StringBuilder sb = new StringBuilder();while ((d=is.read())!=0){if(d==13){continue;}if(d==10){System.out.println(sb.toString());if(sb.toString().equals("over")){break;}sb.delete(0,sb.length() );}else {sb.append((char)d);}}is.close();}}public class Demo9 {public static void main(String[] args) throws Exception{//InputStream is =System.in;InputStreamReader isr = new InputStreamReader(System.in) ;BufferedReader br = new BufferedReader(isr);String line = null;while (true){line = br.readLine();System.out.println(line);if(line.equals("over")){break;}}} }對象流(序列化)
流中流動的數據是對象將一個對象寫入到本地文件中,被稱為對象的序列化將一個本地文件中的對象讀取出來,被稱為對象的反序列化 使用對象流ObjectInputStream: 對象輸出流ObjectOutputStream:對象輸入流注意:序列化對象的類型必須實現Serializable接口。否則不能序列化。如果向將多個對象序列化到本地,可以借助于集合,【思路:將多個對象添加到集合中,將集合的對象寫入到本地文件中,再次讀出來,獲取到的仍然是集合對象,遍歷集合】。 對象中那些字段可以不序列化:1 transient 修飾的字段2 靜態的字段 在要序列化類中添加字段,保證序列化和反序列化是同一個類 private static final long serialVersionUID = 100L;序列化對象類Student 需要實現Serializable 接口
public class Student implements Serializable {private String name;private int age;private String address;public Student(){}public Student(String name,int age,String address){this.name = name;this.age = age;this.address = address;}public String getName(){return name;}public void setName(String name){this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String toString (){return "Student{"+"name,"+name+",age:"+age+",address:"+address+"}";} }// 注釋部分為 單個添加 public class Demo12 {public static void main(String[] args) throws Exception{//序列化ObjectOutputStream sb = new ObjectOutputStream(new FileOutputStream("stu.txt"));Student s1 = new Student("bb",23,"北京");Student s2 = new Student("cc",22,"太原");Student s3 = new Student("dd",18,"北京");ArrayList<Student> sd = new ArrayList<>();sd.add(s1);sd.add(s2);sd.add(s3);sb.writeObject(sd);// sb.writeObject(s1);// sb.writeObject(s2);ObjectInputStream sc = new ObjectInputStream(new FileInputStream("stu.txt"));//Student s11 =(Student) sc.readObject();// Student s22 =(Student) sc.readObject();ArrayList<Student> df =(ArrayList<Student>) sc.readObject();System.out.println(df.toString());// System.out.println(s11.toString());// System.out.println(s22.toString());} }隨機讀取流 RandomAccessFile類
該類的實例支持讀取和寫入隨機訪問文件。
RandomAccessFile是用來訪問那些保存數據記錄的文件的,你就可以用seek( )方法來 訪問記錄, 并進行讀寫了。這些記錄的大小不必相同;但是其大小和位置必須是可知的。 但是該類僅限于操作文件。構造方法
(File file, String mode) 創建一個隨機訪問文件流從File參數指定的文件中讀取,并可選地寫入文件。 RandomAccessFile(String name, String mode) 創建隨機訪問文件流,以從中指定名稱的文件讀取,并可選擇寫入文件。常用方法
void close() 關閉此隨機訪問文件流并釋放與流相關聯的任何系統資源。 long length() 返回此文件的長度。 int read() 從該文件讀取一個字節的數據。 int read(byte[] b) 從該文件讀取最多 b.length字節的數據到字節數組。 int read(byte[] b, int off, int len) 從該文件讀取最多 len個字節的數據到字節數組。 boolean readBoolean() 從此文件讀取一個 boolean 。 byte readByte() 從此文件中讀取一個帶符號的八位值。 char readChar() 從此文件中讀取一個字符。 double readDouble() 從此文件讀取 double 。 float readFloat() 從此文件讀取一個 float 。 int readInt() 從該文件讀取一個帶符號的32位整數。 String readLine() 從此文件中讀取下一行文本。 long readLong() 從該文件中讀取一個帶符號的64位整數。 short readShort() 從此文件中讀取一個已簽名的16位數字。 void seek(long pos) 設置文件指針偏移,從該文件的開頭測量,發生下一次讀取或寫入。 void write(byte[] b) 從指定的字節數組寫入 b.length個字節到該文件,從當前文件指針開始。 void write(byte[] b, int off, int len) 從指定的字節數組寫入 len個字節,從偏移量 off開始寫入此文件。 void write(int b) 將指定的字節寫入此文件。 void writeBoolean(boolean v) 將 boolean寫入文件作為一個字節值。 void writeByte(int v) 將 byte寫入文件作為單字節值。 void writeBytes(String s) 將字符串作為字節序列寫入文件。 void writeChar(int v) 將 char寫入文件作為兩字節值,高字節為先。 void writeChars(String s) 將一個字符串作為字符序列寫入文件。 void writeDouble(double v) 雙參數傳遞給轉換 long使用 doubleToLongBits方法在類 Double ,然后寫入該 long值到該文件作為一個八字節的數量,高字節。 void writeFloat(float v) 浮子參數的轉換 int使用 floatToIntBits方法在類 Float ,然后寫入該 int值到該文件作為一個四字節數量,高字節。 void writeInt(int v) 將 int寫入文件為四個字節,高字節 int 。 void writeLong(long v) 將 long寫入文件為八個字節,高字節為先。 void writeShort(int v) 將 short寫入文件作為兩個字節,高字節優先。案例一: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 沒有泛型
構造方法
Properties() 創建一個沒有默認值的空屬性列表。 Properties(Properties defaults) 創建具有指定默認值的空屬性列表。普通方法
String getProperty(String key) 使用此屬性列表中指定的鍵搜索屬性。 String getProperty(String key, String defaultValue) 使用此屬性列表中指定的鍵搜索屬性。 void list(PrintStream out) 將此屬性列表打印到指定的輸出流。 void list(PrintWriter out) 將此屬性列表打印到指定的輸出流。 void load(InputStream inStream) 從輸入字節流讀取屬性列表(鍵和元素對)。 **void load(Reader reader) 以簡單的線性格式從輸入字符流讀取屬性列表(關鍵字和元素對)。 void loadFromXML(InputStream in) 將指定輸入流中的XML文檔表示的所有屬性加載到此屬性表中。 Enumeration<?> propertyNames() 返回此屬性列表中所有鍵的枚舉,包括默認屬性列表中的不同鍵,如果尚未從主屬性列表中找到相同名稱的鍵。 void save(OutputStream out, String comments) 已棄用 如果在保存屬性列表時發生I / O錯誤,此方法不會拋出IOException。 保存屬性列表的store(OutputStream out, String comments)方法是通過store(OutputStream out, String comments)方法或storeToXML(OutputStream os, String comment)方法。 Object setProperty(String key, String value) 致電 Hashtable方法 put 。 **void store(OutputStream out, String comments) 將此屬性列表(鍵和元素對)寫入此 Properties表中,以適合于使用 load(InputStream)方法加載到 Properties表中的格式輸出流。 void store(Writer writer, String comments) 將此屬性列表(鍵和元素對)寫入此 Properties表中,以適合使用 load(Reader)方法的格式輸出到輸出字符流。 void storeToXML(OutputStream os, String comment) 發出表示此表中包含的所有屬性的XML文檔。 void storeToXML(OutputStream os, String comment, String encoding) 使用指定的編碼發出表示此表中包含的所有屬性的XML文檔。 Set<String> stringPropertyNames() 返回此屬性列表中的一組鍵,其中鍵及其對應的值為字符串,包括默認屬性列表中的不同鍵,如果尚未從主屬性列表中找到相同名稱的鍵。列子1
public class PropertiesTest{public static void main() throws Exception{Properties prop = new Properties();//System.out.println(prop);prop.setProperty("aa", "21");prop.setProperty("bb", "23");prop.setProperty("cc", "23");//System.out.println(prop);System.out.println(prop.get("aa"));//將properties 中的key-value 保存到a.txt中。prop.store(new FileWriter("a.txt"), "comment line");Properties prop2 = new Properties(); prop2.setProperty("key2","value2" );//把a.txt 文件讀取出來加到prop2中prop2.load(new FileInputStream("a.txt"));System.out.println(prop2);} } 輸出結果為: 21 {key2=value2, aa=21, bb=23, cc=23}列子2
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+"吃......");}} 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();} }總結
以上是生活随笔為你收集整理的Java-----关于IO流的总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你的奋斗也许只是一个屁
- 下一篇: matlab进行复数计算