Java IO之字符流

时间:2022-08-18 07:20:34
 public static void main(String[] args) {

         FileWriter fw = null;
         try {
             fw = new FileWriter("/Users/weianlai/demo");
             fw.write("这是一个demo");
             fw.flush();
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if (fw != null) {
                 try {
                     fw.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }

         FileReader fr = null;
         try {
             fr = new FileReader("/Users/weianlai/demo");
             char[] buf = new char[1024];
             int num = 0;
             while ((num = fr.read(buf)) != -1) {
                 System.out.println(new String(new String(buf, 0, num)));
             }
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             if (fr != null) {
                 try {
                     fr.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }

     }