------- android培訓、java培訓、期待與您交流! ----------
21.01 轉換流出現的原因及格式由于字節流操作中文不是特別方便,所以,java就提供了轉換流。
字符流 = 字節流 + 編碼表
21.02 編碼表概述和常見編碼表編碼表:計算機只能識別二進制數據,早期又來是電信號,為了方便應用計算機,讓它可以識別各個國家的文字,就將各個國家的文字用數字來表示,并一一對應,形成一張表,就是編碼表。
簡單的說編碼表就是由字符及其對應的數值組成的一張表。
常見的編碼表:
ASCII:美國標準信息交換碼,用1個字節的7位可以表示
ISO8859-1:拉丁碼表,歐洲碼表,用1個字節的8位表示
GBK2312:中國的中文編碼表
GBK:中國的中文編碼表升級,融合了更多的中文文字符號
GB18030:GBK的取代版本
BIG-5碼 :通行于臺灣、香港地區的一個繁體字編碼方案,俗稱“大五碼”
Unicode:國際標準碼,融合了多種文字,所有的文字都用2個字節表示,Java中使用的就是Unicode碼表
UTF-8:最多用3個字節來表示一個字符(能用一個字節表示的就用一個字節,一個表示不了就用兩個,最多用三個字節)
21.03 String類中的編碼和解碼問題1.public String(byte[] bytes,String charsetName)throws UnsupportedEncodingException
通過使用指定的 charset 解碼指定的 byte 數組,構造一個新的 String。
2.public byte[] getBytes(String charsetName)throws UnsupportedEncodingException
使用指定的字符集將此 String 編碼為 byte 序列,并將結果存儲到一個新的 byte 數組中。
字符串→字節數組 編碼:把看得懂的變成看不懂的
字節數組→字符串 解碼:把看不懂的變成看得懂的
例:
1 public class PRactice 2 { 3 public static void main(String[] args) throws UnsupportedEncodingException 4 { 5 String s = "你好"; 6 //編碼,使用GBK碼表將此字符串編碼為 byte序列 7 byte[] bys = s.getBytes("GBK"); 8 System.out.println(Arrays.toString(bys));//[-60, -29, -70, -61] 9 10 //解碼,使用GBK碼表解碼指定的byte數組11 String ss = new String(bys,"GBK");12 System.out.println(ss);//你好13 }14 }
Windows平臺默認編碼為GBK
21.04 轉換流OutputStreamWriter的使用OutputStreamWriter 字符輸出流
1.public OutputStreamWriter(OutputStream out)
創建使用默認字符編碼的 OutputStreamWriter。
2.public OutputStreamWriter(OutputStream out,String charsetName)throws UnsupportedEncodingException
創建使用指定字符集的 OutputStreamWriter。
例:
//默認編碼GBKOutputStreamWriter osw = new OutputStreamWriter(new FileOutputStrea("D://aa.txt"));osw.write("中國");osw.close();21.05 轉換流InputStreamReader的使用
InputStreamReader 字符輸入流
public InputStreamReader(InputStream in)
創建一個使用默認字符集的 InputStreamReader。
public InputStreamReader(InputStream in,String charsetName) throws UnsupportedEncodingException
創建使用指定字符集的 InputStreamReader。
例:
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 創建對象,默認編碼GBK 6 // InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt")); 7 //指定編碼GBK 8 // InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"), "GBK"); 9 //指定編碼UTF-810 InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"), "UTF-8");11 12 // 讀取數據13 // 一次讀取一個字符14 int ch = 0;15 while ((ch = isr.read()) != -1) 16 {17 System.out.print((char) ch);18 }19 20 // 釋放資源21 isr.close();22 }23 }21.06 字符流的5種寫數據的方式
1.public void write(int c)throws IOException
寫入單個字符。要寫入的字符包含在給定整數值的 16 個低位中,16 高位被忽略。
2.public void write(char[] cbuf)throws IOException
寫入字符數組。
3.public abstract void write(char[] cbuf,int off,int len)throws IOException
寫入字符數組的某一部分。
4.public void write(String str)throws IOException
寫入字符串。
5.public void write(String str,int off,int len)throws IOException
寫入字符串的某一部分。
例:
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 創建對象 6 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D://osw2.txt")); 7 8 // 寫數據 9 // 寫一個字符10 // osw.write('a');11 // osw.write(97);//osw2.txt文件中的內容為aa12 13 // 寫一個字符數組14 // char[] chs = {'a','b','c','d','e'};15 // osw.write(chs);//osw2.txt文件中的內容abcde16 17 // 寫一個字符數組的一部分18 // osw.write(chs,1,3);//osw2.txt文件中的內容bcd19 20 // 寫一個字符串21 // osw.write("helloworld");//osw2.txt文件中的內容helloworld22 23 // public void write(String str,int off,int len):寫一個字符串的一部分24 osw.write("helloworld", 2, 3);//osw2.txt文件中的內容llo25 26 // 刷新緩沖區,可以繼續寫數據27 osw.flush();28 29 // 釋放資源,關閉此流,但要先刷新它30 osw.close();31 }32 }面試題:close()和flush()的區別
A:close()關閉流對象,但是先刷新一次緩沖區。關閉之后,流對象不可以繼續再使用了。
B:flush()僅僅刷新緩沖區,刷新之后,流對象還可以繼續使用。
21.07 字符流的2種讀數據的方式1.public int read()throws IOException
讀取單個字符。在字符可用、發生 I/O 錯誤或者已到達流的末尾前,此方法一直阻塞。
2.public int read(char[] cbuf)throws IOException
將字符讀入數組。在某個輸入可用、發生 I/O 錯誤或者已到達流的末尾前,此方法一直阻塞。
例:
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 InputStreamReader isr1 = new InputStreamReader(new FileInputStream("D://Demo.java")); 6 //一次讀取一個字符 7 int ch = 0; 8 while((ch = isr1.read()) != -1) 9 {10 System.out.print((char)ch);11 }12 13 14 InputStreamReader isr2 = new InputStreamReader(new FileInputStream("D://Demo.java"));15 //一次讀取一個字符數組16 char[] chs = new char[1024];17 int len = 0;18 while((len = isr2.read(chs)) != -1)19 {20 System.out.println(new String(chs,0,len));21 }22 23 isr1.close();24 isr2.close();25 }26 }21.08 字符流復制文本文件案例(轉換流一次讀取一個字符)
數據源:a.txt -- 讀取數據 -- 字符轉換流 -- InputStreamReader
目的地:b.txt -- 寫出數據 -- 字符轉換流 -- OutputStreamWriter
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 InputStreamReader isr = new InputStreamReader(new FileInputStream("D://Demo.java")); 6 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D://bb.txt")); 7 //一次讀取一個字符 8 int ch = 0; 9 while((ch = isr.read()) != -1)10 {11 osw.write(ch);12 }13 14 isr.close();15 osw.close();16 }17 }21.09 字符流復制文本文件案例(使用便捷類)
轉換流的名字比較長,而我們常見的操作都是按照本地默認編碼實現的,所以,為了簡化我們的書寫,轉換流提供了對應的子類。
FileWriter以及FileReader
OutputStreamWriter = FileOutputStream + 編碼表(GBK)
FileWriter = FileOutputStream + 編碼表(GBK)
InputStreamReader = FileInputStream + 編碼表(GBK)
FileReader = FileInputStream + 編碼表(GBK)
例:
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 封裝數據源 6 FileReader fr = new FileReader("D://a.txt"); 7 // 封裝目的地 8 FileWriter fw = new FileWriter("D://b.txt"); 9 10 // 一次一個字符11 // int ch = 0;12 // while ((ch = fr.read()) != -1) 13 //{14 // fw.write(ch);15 //}16 17 // 一次一個字符數組18 char[] chs = new char[1024];19 int len = 0;20 while ((len = fr.read(chs)) != -1) 21 {22 fw.write(chs, 0, len);23 fw.flush();24 }25 26 // 釋放資源27 fw.close();28 fr.close();29 }30 }21.10 字符緩沖輸出流BufferedWriter的使用
將文本寫入字符輸出流,緩沖各個字符,從而提供單個字符、數組和字符串的高效寫入。
可以指定緩沖區的大小,或者接受默認的大小。在大多數情況下,默認值就足夠大了。
構造方法:
1.public BufferedWriter(Writer out)
創建一個使用默認大小輸出緩沖區的緩沖字符輸出流。
2.public BufferedWriter(Writer out,int sz)
創建一個使用給定大小輸出緩沖區的新緩沖字符輸出流。
例:
1 BufferedWriter bw = new BufferedWriter(new FileWriter("d://bw.txt"));2 bw.write("hello");3 bw.write("world");4 bw.write("java");5 bw.flush();6 bw.close();21.11 字符緩沖輸入流BufferedReader的使用
從字符輸入流中讀取文本,緩沖各個字符,從而實現字符、數組和行的高效讀取。
可以指定緩沖區的大小,或者可使用默認的大小。大多數情況下,默認值就足夠大了。
構造方法:
1.public BufferedReader(Reader in)
創建一個使用默認大小輸入緩沖區的緩沖字符輸入流。
2.public BufferedReader(Reader in,int sz)
創建一個使用指定大小輸入緩沖區的緩沖字符輸入流。
例:
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 創建字符緩沖輸入流對象 6 BufferedReader br = new BufferedReader(new FileReader("D://bw.txt")); 7 8 // 方式1 9 // int ch = 0;10 // while ((ch = br.read()) != -1) {11 // System.out.print((char) ch);12 // }13 14 // 方式215 char[] chs = new char[1024];16 int len = 0;17 while ((len = br.read(chs)) != -1) 18 {19 System.out.print(new String(chs, 0, len));20 }21 22 // 釋放資源23 br.close();24 }25 }21.12 字符緩沖流復制文本文件案例
數據源:a.txt -- 讀取數據 -- 字符轉換流 -- InputStreamReader -- FileReader -- BufferedReader
目的地:b.txt -- 寫出數據 -- 字符轉換流 -- OutputStreamWriter -- FileWriter -- BufferedWriter
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 封裝數據源 6 BufferedReader br = new BufferedReader(new FileReader("D://a.txt")); 7 // 封裝目的地 8 BufferedWriter bw = new BufferedWriter(new FileWriter("D://b.txt")); 9 10 // 一次讀寫一個字符數組11 char[] chs = new char[1024];12 int len = 0;13 while ((len = br.read(chs)) != -1) 14 {15 bw.write(chs, 0, len);16 bw.flush();17 }18 19 // 釋放資源20 bw.close();21 br.close();22 }23 }21.13 字符緩沖流的特殊功能
字符緩沖流的特殊方法:
BufferedWriter:
public void newLine()throws IOException
寫入一個行分隔符。行分隔符字符串由系統屬性 line.separator 定義,并且不一定是單個新行 ('/n') 符。
BufferedReader:
public String readLine()throws IOException
讀取一個文本行。通過下列字符之一即可認為某行已終止:換行 ('/n')、回車 ('/r') 或回車后直接跟著換行。包含該行內容的字符串,不包含任何行終止符,如果已到達流末尾,則返回 null
例:
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // write(); 6 read(); 7 } 8 private static void read() throws IOException 9 {10 // 創建字符緩沖輸入流對象11 BufferedReader br = new BufferedReader(new FileReader("D://bw.txt"));12 String line = null;13 while ((line = br.readLine()) != null) 14 {15 System.out.println(line);16 }17 //釋放資源18 br.close();19 }20 21 private static void write() throws IOException 22 {23 // 創建字符緩沖輸出流對象24 BufferedWriter bw = new BufferedWriter(new FileWriter("D://bw.txt"));25 for (int x = 0; x < 10; x++) 26 {27 bw.write("hello" + x);28 bw.newLine();29 bw.flush();30 }31 bw.close();32 }33 }21.14 IO流小結圖解

1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 String srcString = "c://a.txt"; 6 String destString = "d://b.txt"; 7 // method1(srcString, destString); 8 // method2(srcString, destString); 9 // method3(srcString, destString);10 // method4(srcString, destString);11 method5(srcString, destString);12 }13 // 字符緩沖流一次讀寫一個字符串14 private static void method5(String src, String dest)throws IOException 15 {16 BufferedReader br = new BufferedReader(new FileReader(src));17 BufferedWriter bw = new BufferedWriter(new FileWriter(dest));18 19 String line = null;20 while ((line = br.readLine()) != null) 21 {22 bw.write(line);23 bw.newLine();24 bw.flush();25 }26 27 bw.close();28 br.close();29 }30 31 // 字符緩沖流一次讀寫一個字符數組32 private static void method4(String src, String dest)throws IOException 33 {34 BufferedReader br = new BufferedReader(new FileReader(src));35 BufferedWriter bw = new BufferedWriter(new FileWriter(dest));36 37 char[] chs = new char[1024];38 int len = 0;39 while ((len = br.read(chs)) != -1) 40 {41 bw.write(chs, 0, len);42 }43 44 bw.close();45 br.close();46 }47 48 // 字符緩沖流一次讀寫一個字符49 private static void method3(String src, String dest)throws IOException 50 {51 BufferedReader br = new BufferedReader(new FileReader(src));52 BufferedWriter bw = new BufferedWriter(new FileWriter(dest));53 54 int ch = 0;55 while ((ch = br.read()) != -1) 56 {57 bw.write(ch);58 }59 60 bw.close();61 br.close();62 }63 64 // 基本字符流一次讀寫一個字符數組65 private static void method2(String src, String dest)throws IOException 66 {67 FileReader fr = new FileReader(src);68 FileWriter fw = new FileWriter(dest);69 70 char[] chs = new char[1024];71 int len = 0;72 while ((len = fr.read(chs)) != -1) 73 {74 fw.write(chs, 0, len);75 }76 77 fw.close();78 fr.close();79 }80 81 // 基本字符流一次讀寫一個字符82 private static void method1(String src, String dest)throws IOException 83 {84 FileReader fr = new FileReader(src);85 FileWriter fw = new FileWriter(dest);86 87 int ch = 0;88 while ((ch = fr.read()) != -1) 89 {90 fw.write(ch);91 }92 93 fw.close();94 fr.close();95 }96 }21.16 復制圖片的4種方式案例
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 使用字符串作為路徑 6 // String srcString = "c://a.jpg"; 7 // String destString = "d://b.jpg"; 8 // 使用File對象做為參數 9 File srcFile = new File("c://a.jpg");10 File destFile = new File("d://b.jpg");11 12 // method1(srcFile, destFile);13 // method2(srcFile, destFile);14 // method3(srcFile, destFile);15 method4(srcFile, destFile);16 }17 // 字節緩沖流一次讀寫一個字節數組18 private static void method4(File srcFile, File destFile) throws IOException 19 {20 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));21 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));22 23 byte[] bys = new byte[1024];24 int len = 0;25 while ((len = bis.read(bys)) != -1) 26 {27 bos.write(bys, 0, len);28 }29 30 bos.close();31 bis.close();32 }33 34 // 字節緩沖流一次讀寫一個字節35 private static void method3(File srcFile, File destFile) throws IOException 36 {37 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));38 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));39 40 int by = 0;41 while ((by = bis.read()) != -1) 42 {43 bos.write(by);44 }45 46 bos.close();47 bis.close();48 }49 50 // 基本字節流一次讀寫一個字節數組51 private static void method2(File srcFile, File destFile) throws IOException 52 {53 FileInputStream fis = new FileInputStream(srcFile);54 FileOutputStream fos = new FileOutputStream(destFile);55 56 byte[] bys = new byte[1024];57 int len = 0;58 while ((len = fis.read(bys)) != -1) 59 {60 fos.write(bys, 0, len);61 }62 63 fos.close();64 fis.close();65 }66 67 // 基本字節流一次讀寫一個字節68 private static void method1(File srcFile, File destFile) throws IOException 69 {70 FileInputStream fis = new FileInputStream(srcFile);71 FileOutputStream fos = new FileOutputStream(destFile);72 73 int by = 0;74 while ((by = fis.read()) != -1)75 {76 fos.write(by);77 }78 fos.close();79 fis.close();80 }81 }21.17 把集合中的數據存儲到文本文件案例
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 封裝數據源(創建集合對象) 6 ArrayList<String> array = new ArrayList<String>(); 7 array.add("hello"); 8 array.add("world"); 9 array.add("java");10 11 // 封裝目的地12 BufferedWriter bw = new BufferedWriter(new FileWriter("D://a.txt"));13 14 // 遍歷集合15 for (String s : array) 16 {17 // 寫數據18 bw.write(s);19 bw.newLine();20 bw.flush();21 }22 23 // 釋放資源24 bw.close();25 }26 }21.18 隨機獲取文本文件中的姓名案例
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 把文本文件中的數據存儲到集合中 6 BufferedReader br = new BufferedReader(new FileReader("D://a.txt")); 7 ArrayList<String> array = new ArrayList<String>(); 8 String line = null; 9 while ((line = br.readLine()) != null) 10 {11 array.add(line);12 }13 br.close();14 15 // 隨機產生一個索引16 Random r = new Random();17 int index = r.nextInt(array.size());18 19 // 根據該索引獲取一個值20 String name = array.get(index);21 System.out.println("該幸運者是:" + name);22 }23 }21.19 復制單級文件夾案例
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 封裝目錄 6 File srcFolder = new File("e://demo"); 7 // 封裝目的地 8 File destFolder = new File("e://test"); 9 // 如果目的地文件夾不存在,就創建10 if (!destFolder.exists()) 11 {12 destFolder.mkdir();13 }14 15 // 獲取該目錄下的所有文本的File數組16 File[] fileArray = srcFolder.listFiles();17 18 // 遍歷該File數組,得到每一個File對象19 for (File file : fileArray) 20 {21 // System.out.println(file);22 // 數據源:e://demo//e.mp323 // 目的地:e://test//e.mp324 String name = file.getName(); // e.mp325 File newFile = new File(destFolder, name); // e://test//e.mp326 27 copyFile(file, newFile);28 }29 }30 private static void copyFile(File file, File newFile) throws IOException 31 {32 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));33 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));34 35 byte[] bys = new byte[1024];36 int len = 0;37 while ((len = bis.read(bys)) != -1) 38 {39 bos.write(bys, 0, len);40 }41 bos.close();42 bis.close();43 }44 }21.20 復制指定目錄下指定后綴名的文件并修改名稱案例
需求:復制指定目錄下的指定文件,并修改后綴名。
指定的文件是:.java文件
指定的后綴名是:.jad
指定的目錄是:jad
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 封裝目錄 6 File srcFolder = new File("e://java"); 7 // 封裝目的地 8 File destFolder = new File("e://jad"); 9 // 如果目的地目錄不存在,就創建10 if (!destFolder.exists()) 11 {12 destFolder.mkdir();13 }14 15 // 獲取該目錄下的java文件的File數組16 File[] fileArray = srcFolder.listFiles(new FilenameFilter() 17 {18 @Override19 public boolean accept(File dir, String name) 20 {21 return new File(dir, name).isFile() && name.endsWith(".java");22 }23 });24 25 // 遍歷該File數組,得到每一個File對象26 for (File file : fileArray) 27 {28 // System.out.println(file);29 // 數據源:e:/java/DataTypeDemo.java30 // 目的地:e://jad/DataTypeDemo.java31 String name = file.getName();32 File newFile = new File(destFolder, name);33 copyFile(file, newFile);34 }35 36 // 在目的地目錄下改名37 File[] destFileArray = destFolder.listFiles();38 for (File destFile : destFileArray)39 {40 // System.out.println(destFile);41 // e:/jad/DataTypeDemo.java42 // e://jad//DataTypeDemo.jad43 String name =destFile.getName(); //DataTypeDemo.java44 String newName = name.replace(".java", ".jad");//DataTypeDemo.jad45 46 File newFile = new File(destFolder,newName);47 destFile.renameTo(newFile);48 }49 }50 private static void copyFile(File file, File newFile) throws IOException 51 {52 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));53 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));54 55 byte[] bys = new byte[1024];56 int len = 0;57 while ((len = bis.read(bys)) != -1) 58 {59 bos.write(bys, 0, len);60 }61 62 bos.close();63 bis.close();64 }65 }21.21 復制多級文件夾案例
需求:復制多極文件夾
數據源:E:/JavaSE/day21/code/demos
目的地:E://
分析:
A:封裝數據源File
B:封裝目的地File
C:判斷該File是文件夾還是文件
a:是文件夾
就在目的地目錄下創建該文件夾
獲取該File對象下的所有文件或者文件夾File對象
遍歷得到每一個File對象
回到C
b:是文件就復制(字節流)
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 // 封裝數據源File 6 File srcFile = new File("E://JavaSE//day21//code//demos"); 7 // 封裝目的地File 8 File destFile = new File("E://"); 9 10 // 復制文件夾的功能11 copyFolder(srcFile, destFile);12 }13 private static void copyFolder(File srcFile, File destFile)throws IOException {14 // 判斷該File是文件夾還是文件15 if (srcFile.isDirectory()) 16 {17 // 文件夾18 File newFolder = new File(destFile, srcFile.getName());19 newFolder.mkdir();20 21 // 獲取該File對象下的所有文件或者文件夾File對象22 File[] fileArray = srcFile.listFiles();23 for (File file : fileArray)24 {25 copyFolder(file, newFolder);26 }27 } 28 else 29 {30 // 文件31 File newFile = new File(destFile, srcFile.getName());32 copyFile(srcFile, newFile);33 }34 }35 36 private static void copyFile(File srcFile, File newFile) throws IOException 37 {38 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));39 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));40 41 byte[] bys = new byte[1024];42 int len = 0;43 while ((len = bis.read(bys)) != -1) 44 {45 bos.write(bys, 0, len);46 }47 bos.close();48 bis.close();49 }50 }21.22 鍵盤錄入學生信息按照總分排序并寫入文本文件案例
Student類同day17 17.16
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() 6 { 7 @Override 8 public int compare(Student s1, Student s2) 9 {10 //按總分比較11 int num1 = s2.getSum() - s1.getSum();12 //總分相同按語文成績比較13 int num2 = num1==0?s1.getChinese() - s2.getChinese():num1;14 //語文成績相同按數學成績比較15 int num3 = num2==0?s1.getMath() - s2.getMath():num2;16 //數學成績相同按英語成績比較17 int num4 = num3==0?s1.getChinese() - s2.getChinese():num3;18 //英語成績相同按姓名比較19 int num5 = num4==0?s1.getName().compareTo(s2.getName()):num4;20 return num5;21 }22 });23 for (int i = 1; i <= 5; i++) 24 {25 Scanner sc = new Scanner(System.in);26 System.out.println("請輸入第"+i+"位學生的姓名");27 String name = sc.nextLine();28 System.out.println("請輸入第"+i+"位學生的語文成績");29 String chinese = sc.nextLine();30 System.out.println("請輸入第"+i+"位學生的數學成績");31 String math = sc.nextLine();32 System.out.println("請輸入第"+i+"位學生的英語成績");33 String english = sc.nextLine();34 35 Student s = new Student(name, Integer.parseInt(chinese), Integer.parseInt(math), Integer.parseInt(english));36 ts.add(s);37 }38 // 遍歷集合,把數據寫到文本文件39 BufferedWriter bw = new BufferedWriter(new FileWriter("D://students.txt"));40 bw.write("學生信息如下:");41 bw.newLine();42 bw.flush();43 bw.write("姓名/t語文/t數學/t英語/t總分");44 bw.newLine();45 bw.flush();46 for (Student s : ts) 47 {48 StringBuilder sb = new StringBuilder();49 sb.append(s.getName()).append("/t").append(s.getChinese())50 .append("/t").append(s.getMath()).append("/t")51 .append(s.getEnglish()).append("/t").append(s.getSum());52 bw.write(sb.toString());53 bw.newLine();54 bw.flush();55 }56 // 釋放資源57 bw.close();58 System.out.println("學生信息存儲完畢");59 }60 }21.23 自定義類模擬BufferedReader的readLine()功能案例
用Reader模擬BufferedReader的readLine()功能
readLine():一次讀取一行,根據換行符判斷是否結束,只返回內容,不返回換行符
1 public class MyBufferedReader 2 { 3 private Reader r; 4 5 public MyBufferedReader(Reader r) 6 { 7 this.r = r; 8 } 9 10 //思考:寫一個方法,返回值是一個字符串。11 public String readLine() throws IOException 12 {13 /*14 * 要返回一個字符串,看看r對象的兩個讀取方法,一次讀取一個字符或者一次讀取一個字符數組15 * 很容易想到字符數組比較好,但是不能確定這個數組的長度是多長16 * 所以,只能選擇一次讀取一個字符。17 * 但是呢,這種方式的時候,我們再讀取下一個字符的時候,上一個字符就丟失了18 * 所以,應該定義一個臨時存儲空間把讀取過的字符給存儲起來。19 * 這個用誰比較和是呢?數組,集合,字符串緩沖區三個可供選擇。20 * 經過簡單的分析,最終選擇使用字符串緩沖區對象。并且使用的是StringBuilder21 */22 StringBuilder sb = new StringBuilder();23 24 // 做這個讀取最麻煩的是判斷結束,但是在結束之前應該是一直讀取,直到-125 26 /*27 hello28 world29 java 30 31 10410110810811132 11911111410810033 106971189734 /r 13 /n 1035 */36 37 int ch = 0;38 while ((ch = r.read()) != -1) 39 { //104,101,108,108,11140 if (ch == '/r') 41 {42 continue;43 }44 45 if (ch == '/n') 46 {47 return sb.toString(); //hello48 } 49 else 50 {51 sb.append((char)ch); //hello52 }53 }54 55 // 為了防止數據丟失,判斷sb的長度不能大于056 if (sb.length() > 0) 57 {58 return sb.toString();59 }60 return null;61 }62 63 64 //關閉方法65 public void close() throws IOException 66 {67 this.r.close();68 }69 }70 21.24 LineNumberReader的使用案例
例:
1 public class Practice 2 { 3 public static void main(String[] args) throws IOException 4 { 5 LineNumberReader lnr = new LineNumberReader(new FileReader("D://students.txt")); 6 String line = null; 7 lnr.setLineNumber(9);//設置行號 8 while((line = lnr.readLine()) != null) 9 {10 //獲取行號11 System.out.println(lnr.getLineNumber()+":"+line);12 }13 }14 }運行結果:
10:學生信息如下:11:姓名 語文 數學 英語 總分12:gdf 45 76 54 17513:ftg 47 45 68 16014:dcf 25 64 57 14615:wdsa 23 45 76 14416:ef 56 34 16 106
21.25 自定義類模擬LineNumberReader的獲取行號功能案例
1 //方式1: 2 public class MyLineNumberReader 3 { 4 private Reader r; 5 private int lineNumber = 0; 6 7 public MyLineNumberReader(Reader r) 8 { 9 this.r = r;10 }11 12 public int getLineNumber() 13 {14 // lineNumber++;15 return lineNumber;16 }17 18 public void setLineNumber(int lineNumber)19 {20 this.lineNumber = lineNumber;21 }22 23 public String readLine() throws IOException 24 {25 lineNumber++;26 27 StringBuilder sb = new StringBuilder();28 29 int ch = 0;30 while ((ch = r.read()) != -1) 31 {32 if (ch == '/r') 33 {34 continue;35 }36 37 if (ch == '/n')38 {39 return sb.toString();40 } 41 else 42 {43 sb.append((char) ch);44 }45 }46 47 if (sb.length() > 0) 48 {49 return sb.toString();50 }51 52 return null;53 }54 55 public void close() throws IOException 56 {57 this.r.close();58 }59 }60 61 //方式2:繼承21.29的BufferedReader類62 public class MyLineNumberReader extends MyBufferedReader63 {64 private Reader r;65 66 private int lineNumber = 0;67 68 public MyLineNumberReader(Reader r) 69 {70 super(r);71 }72 73 public int getLineNumber() 74 {75 return lineNumber;76 }77 78 public void setLineNumber(int lineNumber) 79 {80 this.lineNumber = lineNumber;81 }82 83 @Override84 public String readLine() throws IOException85 {86 lineNumber++;87 return super.readLine();88 }89 }新聞熱點
疑難解答