更新時間:2023-02-08 16:07:38 來源:動力節點 瀏覽404次
1.字符輸入流
1.java.io.Reader:字符輸入流,抽象類
具體的子類:字節輸入流通向字符輸入流的橋梁:InputStreamReader
2.字符緩沖輸入流:
構造方法:
public InputStreamReader(InputStream in):使用默認字符集進行解碼
public InputStreamReader(InputStream in,String charsetName)throws UnsupportedEncodingException:使用指定的字符集解碼
讀的方式:
public int read() throws IOException:一次讀取一個字符
public int read(char[] cbuf)throws IOException:一次讀取一個字符數組
3.public class ReaderDemo{
public static void mian(String[] args) throws Exception{
//創建字符緩沖輸入流對象
InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"));
//一次讀取一個字符數組
char[] chs = new char[1024];
int len = 0;
while((len=isr.read(chs))!=-1){
sout(new String(chs,0,len));
}
isr.close();
}
}
2.字符輸出流
1.java.io.Writer:字符輸出流,抽象類
具體的子類:OutputStreamWriter:字符轉換輸出流
2.構造方法:
public OutputStreamWriter(OutputStream out):使用平臺默認字符集編碼
public OutputStreamWriter(OutputStream out,String charsetName):使用指定的字符集進行編碼
寫的功能:
public void write(char[] cbuf) throws IOException:寫一個字符數組
public abstract void write(char[] cbuf,int off,int len)throws IOException:從指定位置開始寫入一部分字符數組
public void write(String str)throws IOExceotion:寫入字符串
public void write(String str,int off,int len)throws IOException:寫字符串的一部分
public void write(int c)throws IOException:寫一個字符
3.代碼實現:
public class WriteDemo{
public static void main(String[] args) throw Exception{
//創建字符緩沖輸出流對象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"));
//寫數據
osw.write("hello,字符流我來了");
//寫一個字符
osw.write(97);
//寫一個字符數組
char[] chs = {"高","圓","圓"};
osw.write(chs);
//關閉前刷新流
osw.flush();
osw.close();
}
}
3.使用字符轉換輸入流和轉換輸出流來復制一個文本
1.字符流里直接操作文件--->字符轉換流的便捷類
直接子類:public FileReader(String fileName) throws FileNotFoundException
public FileWriter(String fileName) throws IOException
2.代碼實現:
public class CopyFileTest{
public static void main(String[] args) throws Exception{
method1("BufferedOutputStreamDemo.java","D:\\EE_2113\\day27_pm\\code\\copy4.java") ;
method2("BufferedOutputStreamDemo.java","D:\\EE_2113\\day27_pm\\code\\copy2.java") ;
}
//使用字符轉換流的便捷類來直接操作文件---一次讀取一個字符數組
private static void method1(String sourch,String dest) throws Exception{
//創建FileReader類對象
FileReader fr = new FileReader(source);
//創建FileWriter類對象
FileWriter fw = new FileWriter(dest);
//一次讀取一個字符數組
char[] chs = new char[1024];
int len = 0;
while((len = fr.read(chs))!=-1){
fw.write(chs,0,len);
}
fw.close();
fr.close();
}
//使用字符轉換輸入流一次讀取一個字符數組
private static void method2(String source,String dest) throws Exception{
InputStreamReader isr = new InptStreamReader(new FileInputStream(source));
OutputStreamWriter osw = new OutputStreamReader(new FileOutputStream(dest));
char[] chs = new char[1024];
int len = 0 ;
while((len=isr.read(chs))!= -1){
osw.write(chs,0,len);
}
osw.close();
isr.close();
}
}
以上就是動力節點小編介紹的"讓我們來看看字符輸出流",希望對大家有幫助,如有疑問,請在線咨詢,有專業老師隨時為您務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習