做網(wǎng)站和網(wǎng)頁(yè)區(qū)別/seo黑帽教學(xué)網(wǎng)
-
標(biāo)準(zhǔn)輸入輸出流
1. System.in 標(biāo)準(zhǔn)輸入流
? ? ? ? 本質(zhì)上是一個(gè)InputString,對(duì)應(yīng)鍵盤,表示從鍵盤輸入。
????????定義:public final static InputStream in = null;
? ? ? ? 所以?Scanner scanner = new Scanner(System.in); 會(huì)從鍵盤中獲取數(shù)據(jù)
2.?System.out 標(biāo)準(zhǔn)輸出流
? ? ? ? 本質(zhì)上是一個(gè)OutputStream,對(duì)應(yīng)顯示器,不過(guò)被包裝成了PrintStream,表示在顯示器上輸出。
????????定義:public final static PrintStream out = null;
? ? ? ? 所以?System.out.println(); 就是使用 out 對(duì)象將數(shù)據(jù)輸出到顯示器上。
-
轉(zhuǎn)換流
1. 為了解決使用讀寫源文件時(shí)出現(xiàn)的亂碼問(wèn)題(字符編碼不一致),引出轉(zhuǎn)換流
2.?InputStreamReader 是 Reader 的子類,代碼可以將 InputStream 字節(jié)流包裝(轉(zhuǎn)換)成指定編碼的 Reader 字符流
3. OutputStreamWriter 是 Writer 的子類,可以將 OutputStream 字節(jié)流包裝(轉(zhuǎn)換)成指定編碼的 Writer 字符流
4. 當(dāng)處理存文本數(shù)據(jù)時(shí),使用字符流的效率更高
-
InputStreamReader 類的常用方法
1.?使用特定編碼方式包裝字節(jié)輸入流的構(gòu)造方法
????????public InputStreamReader(InputStream in, Charset cs)
????????參數(shù):in - 一個(gè) InputStream 子類下的輸入流
? ? ? ? ? ? ? ? ? ?cs - 一個(gè)字符串類型的字符集
2. 獲得該轉(zhuǎn)換流所使用的編碼方式
????????public String getEncoding()
3. 關(guān)閉流
????????public void close() throws IOException
? ? ? ? 說(shuō)明:不管包裝了多少個(gè)流,只需要關(guān)閉最外層的流就行
public class InputStreamReader01 {public static void main(String[] args) throws IOException {// 演示使用轉(zhuǎn)換流解決中文亂碼的問(wèn)題, 通過(guò)轉(zhuǎn)換流 將字節(jié)流 轉(zhuǎn)換成指定編碼的字符流String filePath = "d:\\a.txt";FileInputStream fis = new FileInputStream(filePath);// 將字節(jié)流轉(zhuǎn)換成轉(zhuǎn)換流// InputStreamReader isr = new InputStreamReader(fis, "UTF-8");InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);// 將轉(zhuǎn)換流又轉(zhuǎn)換成包裝流BufferedReader br = new BufferedReader(isr);// 讀取String s = br.readLine();System.out.println("編碼方式為: " + isr.getEncoding());System.out.println("讀取到的第一行為: " + s);br.close();}
}
-
OutputStreamWriter 類的常用方法
1.?使用特定編碼方式包裝字節(jié)輸出流的構(gòu)造方法
????????public OutputStreamWriter(OutputStream out, Charset cs)
? ? ? ? 參數(shù):out - 一個(gè) OutputStream 子類下的輸出流
? ? ? ? ? ? ? ? ? ?cs - 一個(gè)字符串類型的字符集
2. 關(guān)閉流
????????public void close() throws IOException
? ? ? ? 說(shuō)明:不管包裝了多少個(gè)流,只需要關(guān)閉最外層的流就行,如果不關(guān)閉或刷新流,東西寫不進(jìn)去
public class OutputStreamWriter01 {public static void main(String[] args) throws IOException {String filePath = "d:\\a.txt";FileOutputStream fos = new FileOutputStream(filePath, true);OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);BufferedWriter fw = new BufferedWriter(osw);fw.newLine();fw.write("通過(guò)轉(zhuǎn)換流寫入");fw.close();}
}