轉(zhuǎn)換流:都是字節(jié)流轉(zhuǎn)向字符流
InputStreamReader
OutputStreamWriter
轉(zhuǎn)換流的作用:
- 可以把字節(jié)流轉(zhuǎn)換成字符流。
- 可以指定任意的碼表進(jìn)行讀寫數(shù)據(jù)。
FileReader---------- 默認(rèn)gbk
FileWriter ---------默認(rèn)gbk
***疑問(wèn):
為什么讀取數(shù)據(jù)或?qū)懭霐?shù)據(jù)的時(shí)候不直接使用BufferedReader/BufferedWriter呢? ***
除了上面可以指定碼表的功能外,還有一個(gè)原因就是好有的函數(shù)返回的就是字節(jié)流,或者一些第三方框架就是使用的字節(jié)流,這個(gè)是我們沒(méi)有辦法改變的; 當(dāng)時(shí)我們?cè)谧x寫數(shù)據(jù)的時(shí)候又希望使用字符流,所以誕生了這個(gè)轉(zhuǎn)換流
public class Demo3 {
public static void main(String[] args) throws IOException {
// readTest1();
// writeTest1();
// writeData();
readData();
}
//指定碼表讀取數(shù)據(jù)
public static void readData() throws IOException{
FileInputStream fileInputStream = new FileInputStream("F:\\a.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
char[] buf = new char[1024];
int length = 0 ;
while((length = inputStreamReader.read(buf))!=-1){
System.out.println(new String(buf,0,length));
}
//關(guān)閉資源
inputStreamReader.close();
}
//指定碼表進(jìn)行寫數(shù)據(jù)
public static void writeData() throws IOException{
FileOutputStream fileOutputStream = new FileOutputStream("f:\\a.txt"); // FileWriter 默認(rèn)使用的碼表是gbk碼表,而且不能指定碼表寫。
OutputStreamWriter fileWriter = new OutputStreamWriter(fileOutputStream, "utf-8");
fileWriter.write("中國(guó)");
fileWriter.close();
}
//把輸出字節(jié)流轉(zhuǎn)換成輸出字符流
public static void writeTest1() throws IOException{
FileOutputStream fileOutputStream = new FileOutputStream("f:\\a.txt");
String data = "hello world";
//需求:要把輸出字節(jié)流轉(zhuǎn)換成輸出字符流. //字節(jié)流向文件輸出數(shù)據(jù)的時(shí)候需要借助String類的getbyte功能,我想使用字符流.
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
//寫出數(shù)據(jù)
writer.write(data);
//關(guān)閉資源
writer.close();
}
//把輸入字節(jié)流轉(zhuǎn)換成了輸入字符流 -----> InputStreamReader
public static void readTest1() throws IOException{
//先獲取標(biāo)準(zhǔn) 的輸入流
InputStream in = System.in;
//把字節(jié)流轉(zhuǎn)換成字符流
InputStreamReader inputStreamReader = new InputStreamReader(in);
//一次讀取一行的功能
// BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = bufferedReader.readLine())!=null){
System.out.println(line);
}
}
}