字符流的相關操作(3+1)

字節流的相關操作:

介紹:字符流:讀寫單位是字符

 java.io.Reader:輸入流的頂級父類
 java.io.Writer:輸出流的頂級父類

1.OutputStreamWriter+InputStreamReader

  PS:轉換流,本質就是一個個讀寫字符。

        同時字節流轉換爲字符流,給其他高級流使用,

2.BufferedReader按行讀取字符串+BufferedWriter(略)

3.PrinterWriter具有自動行刷新的緩衝字符輸出流+PrintReader

   PS:可以處理字節流,字符流,第二個參數是true具有自動行刷新功能

4.Note(筆記本案例)

*******************************************************************************************

public class A_OutputStreamWriter {
public static void main(String[] args) throws Exception {
FileOutputStream fos=new FileOutputStream("demo1.txt");
OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
osw.write("我愛北京天安門");
osw.write("天安門上太陽昇");
System.out.println("寫出完畢!");
osw.close();
}
}

public class A_InputStreamReader {
public static void main(String[] args) throws Exception {
FileInputStream fis=new FileInputStream("demo1.txt");
InputStreamReader isr=new InputStreamReader(fis,"utf-8");
int d=-1;
while((d=isr.read())!=-1){
System.out.print((char)d);
}
isr.close();
}
}

public class B_BufferedReader {
public static void main(String[] args) throws Exception {
FileInputStream fis=new FileInputStream("src/day03/BRDemo.java");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr);
 //BufferedReader提供了按行讀取的方法
 //String readLine();
 //連續讀取若干個字符,直到讀取到換行符爲止
 //並以換行符之間的字符數組以字符串的形式返回
 //返回值爲null表示讀取到了文件末尾
 //注意:字符串不包含最後的換行符

String line=null;
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
}
}

public class B_PrintWriter1 {
public static void main(String[] args) throws Exception, Exception {
//字節流,字符流(轉換流),緩衝字符流,本體
PrintWriter pw=new PrintWriter("pw.txt","utf-8");
pw.println("鋤禾日當午");
pw.println("清明上河圖");
System.out.println("寫出完畢");
pw.close();
}
}

public class B_PrintWriter2 {
public static void main(String[] args) throws Exception {
FileOutputStream fos=new FileOutputStream("demo1.txt");
OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
PrintWriter pw=new PrintWriter(osw,true);
pw.print("呵呵");//print沒有
pw.println("呵呵");//這個有自動行刷新
System.out.println("寫出完畢!");
pw.close();
}
}

public class C_Note {
public static void main(String[] args) throws Exception {
Scanner scanner=new Scanner(System.in);
System.out.println("請輸入文件名");
String fileName=scanner.nextLine();

FileOutputStream fos=new FileOutputStream(fileName);
OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");
PrintWriter pw=new PrintWriter(osw,true);//自動行刷新,必須是println纔行
System.out.println("請開始輸入內容!");
String line=null;
while(true){
line=scanner.nextLine();
if("exit".equals(line)){
System.out.println("再見!");
break;
}
pw.println(line);
//pw.flush();,因爲可以自動行刷新了
}
pw.close();
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章