一站式企业服务汽车类网站建设预算
 第五章:IO流 (java.io包中) 
 
 
 三、字符流  
 
 
 1. 字符流的父类(抽象类): 
 
 Reader:字符输入流  
   对应的操作为读操作  
   功能方法:read方法  
   Writer:字符输出流  
   对应的操作为写操作  
   功能方法:write方法 
  2. 文件字符流 
   (1) FileWriter文件字符输出流,继承Writer中的方法:  
  public void write(int n):将单个字符写入到文件中  
   (2) FileReader文件字符输入流,继承Reader中的方法:  
   public int read():一次读取一个字符的内容 
  3. 字符过滤流 
  (1) BufferedReader:  
   功能方法,readLine():一次性读取一行内容,返回内容为String,读取达到尾部,返回-1  
   (2) PrintWriter  
   println(参数); 
  4. 桥转换流 
  InputStreamReader/OutputStreamWriter:桥转换流;设置 编解码格式 
  package testio2;  
   import java.io.*;  
   // 桥转换流: ctr+A -> ctr+x -> 设置格式 -> ctr+v ->ctr+s  
   public class TestInputStreamReader {  
   public static void main(String[] args) throws IOException {  
   // 1. 创建文件字节输入流对象  
   FileInputStream fis = new FileInputStream("file/k.txt");  
   // 2. 创建桥转换流对象,设置编解码格式  
   InputStreamReader isr = new InputStreamReader(fis,"GBK");  
   // 3. 创建过滤流  
   BufferedReader br = new BufferedReader(isr);  
   // 4. 读操作  
   while(true){  
   String n= br.readLine();  
   if(n==null) break;  
   System.out.println(n);  
   }  
   // 5. 关闭流  
   br.close();  
   }  
   }  
  package testio2;  
   import java.io.*;  
   // 桥转换流: ctr+A -> ctr+x -> 设置格式 -> ctr+v ->ctr+s  
   public class TestOutputStreamWriter {  
   public static void main(String[] args) { 
  PrintWriter pw = null;  
   try {  
   FileOutputStream fos = new FileOutputStream("file/my.txt");  
   OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");  
   pw = new PrintWriter(osw);  
   pw.println("嘻嘻");  
   pw.println("哈哈");  
   pw.print("呵呵");  
   }catch (IOException e){  
   e.printStackTrace();  
   }finally {  
   if(pw !=null) {  
   pw.close();  
   }  
   }  
   }  
   } 
  四、File类  
   1. IO流:对文件中的内容进行操作。 File类:对文件自身进行操作,例如:删除文件,文件重新命 
  名等。  
   2. 操作: 
  public class TestFile {  
   public static void main(String[] args) throws IOException {  
   File file = new File("file/hh.txt");  
   /*System.out.println(file.exists());  
   file.createNewFile();*/  
   if(file.exists()){  
   System.out.println("文件存在,则直接使用...");  
   FileInputStream fis = new FileInputStream(file);  
   }else{  
   System.out.println("文件不存在,创建新的文件....");  
   file.createNewFile();  
   }  
   }  
   } 
  