下面分別為1.7和1.4提供的API
1 Files.newBufferedReader(Paths.get(""), StandardCharsets.UTF_8); 2 new BufferedReader(new InputStreamReader(new FileInputStream(new File("")), StandardCharsets.UTF_8));
1.7的API
1 Files.newBufferedReader(Paths.get(""), StandardCharsets.UTF_8);
newBufferedReader靜態方法
查看2784行InputStreamReader構造函數
查看132行靜態方法
查看85行構造函數
StreamDecoder接收的參數CharsetDecoder為cs.newDecoder()。
1.4的API
1 new BufferedReader(new InputStreamReader(new FileInputStream(new File("")), StandardCharsets.UTF_8));
片段1,第6行,new BufferedReader(reader),都是將reader作為參數傳入。下面重點查看InputStreamReader構造函數
查看116行靜態方法
查看78行構造函數,下圖231行最終調用下圖237行最終的構造函數
StreamDecoder接收的參數CharsetDecoder為cs.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)。
兩者的區別為StreamDecoder接收的參數,1.4API多了如下兩個參數
項目中遇到,UTF-8讀取未知字符類型文件,前者報錯導致程序中斷,后者正常。通過編寫代碼,驗證適用的字符類型,前者才能讀取成功。
應該是字符類型不對時,后者自適應讀取,查看源碼時需要導入包含源碼的src.zip包。
如果字符類型不確定時,優先采用1.4API。
不對之處,敬請指正。