Java的字元流
阿新 • • 發佈:2021-07-17
Java的字元流
字元輸入流
package com.cnblogs; import java.io.*; /* 本類用於測試字元流的讀取 */ public class TestIn2 { public static void main(String[] args) { // method();//普通 method2();//高效 } private static void method() { // Reader in2 = new Reader(); 抽象的 Reader in2 = null; try { in2 = new FileReader("E:\\ready\\1.txt"); int result = 0; while((result = in2.read()) != -1){ System.out.println(result); } } catch (Exception e) { e.printStackTrace(); }finally { try { in2.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void method2() { Reader in2 = null; try { in2 =new BufferedReader(new FileReader("E:\\ready\\1.txt")); int result = 0; while((result = in2.read()) != -1){ System.out.println(result); } } catch (Exception e) { e.printStackTrace(); }finally { try { in2.close(); } catch (IOException e) { e.printStackTrace(); } } } }
字元輸出流
package com.cnblogs; import java.io.*; /* 本類用於測試字元輸出流 */ public class TestOut2 { public static void main(String[] args) { method(); // method2(); } private static void method() { Writer out2 = null; try { String date = "hello World!!!"; out2 = new FileWriter("E:\\ready\\1.txt",true); // out2.write(99); // out2.write(99); // out2.write(99); // out2.write(99); // out2.write(99); out2.write(date); } catch (Exception e) { e.printStackTrace(); } finally { try { out2.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void method2() { Writer out2 = null; try { out2 =new BufferedWriter(new FileWriter("E:\\ready\\1.txt",true)); out2.write(98); out2.write(98); out2.write(98); out2.write(98); out2.write(98); } catch (Exception e) { e.printStackTrace(); } finally { try { out2.close(); } catch (IOException e) { e.printStackTrace(); } } } }