分別使用(字元流)和(位元組流)對檔案進行讀寫操作
阿新 • • 發佈:2019-01-23
一.使用(字元流)對檔案進行讀寫操作
執行結果:/* * 使用字元流對檔案進行讀寫操作 */ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; public class T04 { public static void main(String[] args) throws Exception{ String value = "中國風\n"; String value2 = "a 中國風\n"; // 向檔案中寫入內容 PrintWriter pw = new PrintWriter("temp.txt","UTF-8"); pw.write(value); pw.write(value2); pw.close(); // 從檔案中讀取內容 BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream("temp.txt"),"utf-8")); String b; while((b = br.readLine())!=null){ // 按行讀取 System.out.println(b); } br.close(); } }
中國風
a 中國風
二.使用(位元組流)對檔案進行讀寫操作執行結果:/* * 使用位元組流對檔案進行讀寫操作 */ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; public class T05 { public static void main(String[] args) throws Exception{ String value = "中國風\n"; String value2 = "a 中國風\n"; // 向檔案中寫入內容 File f = new File("temp.txt"); FileOutputStream fos = new FileOutputStream(f); fos.write(value.getBytes("UTF-8")); // 可以指定編碼 fos.write(value2.getBytes()); fos.close(); // 從檔案中讀取內容 FileInputStream fis = new FileInputStream(f); byte b[] = new byte[(int)f.length()]; int len = fis.read(b); // 讀取後返回長度 fis.close(); System.out.println(new String(b)); } }
涓浗椋�
a 中國風