這里演示 最基本的 字符流讀寫文件构订。 基礎(chǔ)比天大,基礎(chǔ)牢固的情況下就可以做更復(fù)雜的東西避矢。
字符可以理解為字節(jié)的組裝悼瘾,觀察很多代碼會(huì)發(fā)現(xiàn):
字節(jié)是byte為基準(zhǔn) 讀出來是一個(gè)一個(gè)byte囊榜。
字符是char為基準(zhǔn) 讀出來是一個(gè)一個(gè)char。
所以在代碼里面會(huì)用相應(yīng)的byte[]/char[] 數(shù)組來裝載它們亥宿。
字符流的提供意味著 我們可以直接讀文本中的字符 省略掉了字符-字節(jié) 相互轉(zhuǎn)化的過程了卸勺。
熟悉了字符流讀寫 字節(jié)流就更簡(jiǎn)單了,只是存取數(shù)據(jù)的載體變成了char數(shù)組:
注意:
代碼第四行烫扼,這里把字符流創(chuàng)建 寫在了try()里面 所以不需要手動(dòng)close了曙求。
這是一種比較推薦的方式 安全又簡(jiǎn)便
public class ReaderAndWriteStream {
public static void main(String[] args) {
File file = new File("e:/SCfile/serral.txt");
try (FileWriter fileWriter = new FileWriter(file)){ // 代碼第四行
String str="serral is the best non-Korean gamer!";
char[] cs =str.toCharArray();
fileWriter.write(cs);
}catch (IOException e){
e.printStackTrace();
}
if(file.exists()){
System.out.println("先確認(rèn)文件存在");
try (FileReader fileReader = new FileReader(file)){
char[] all = new char[(int) file.length()];
fileReader.read(all);
String string = new String(all);
System.out.println("文件中讀取的內(nèi)容為"+string);
}catch (IOException e){
e.printStackTrace();
}
}
}
}