I/O字符流
/* * 编码格式 * utf-8:国际标准通用 * GBK:包含中文 * ASICLL:美国标准 美国文字全部由26个字母组成,然后数字 128个 * */ public void utf8Test() throws UnsupportedEncodingException { String s="中国"; byte[] defult=s.getBytes(); System.out.println(Arrays.toString(defult)); System.out.println(new String(defult,"UTF-8")); byte[] utf8=s.getBytes("UTF-8"); System.out.println(Arrays.toString(utf8)); byte[] gbk=s.getBytes("GBK"); System.out.println(Arrays.toString(gbk)); System.out.println(new String(gbk,"UTF-8")); } public void streamTest() throws IOException { String path="E:\\Java\\00_0\\2.txt"; OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(path,true),"UTF-8"); osw.write("测试字符流"); //字符流必须先flush():将写入缓存中的字符写入到文本。close的时候会自动调用 osw.flush(); InputStreamReader isr=new InputStreamReader(new FileInputStream(path),"UTF-8"); char[] arr=new char[1024]; int len; while ((len=isr.read(arr))!=-1){ System.out.printf(new String(arr,0,len)); } osw.close(); isr.close(); } /* * 简化版本 * */ public void fileTest() throws IOException { String path="E:\\Java\\00_0\\3.txt"; FileWriter fw=new FileWriter(path, Charset.forName("UTF-8"),true); fw.write("测试FileWriter"); fw.flush(); FileReader fr=new FileReader(path,Charset.forName("UTF-8")); char[] arr=new char[1024]; int len; while ((len=fr.read(arr))!=-1){ System.out.println(new String(arr)); } fw.close(); fr.close(); } /* * 一次一个字节读取 * */ public void fileTest1() throws IOException { String path="E:\\Java\\00_0\\3.txt"; FileWriter fw=new FileWriter(path, Charset.forName("UTF-8"),true); fw.write("测试FileWriter"); fw.flush(); FileReader fr=new FileReader(path,Charset.forName("UTF-8")); int c; while ((c=fr.read())!=-1){ System.out.print((char)c); } fw.close(); fr.close(); } public void buffedTest() throws IOException { String path="E:\\Java\\00_0\\4.txt"; BufferedWriter bw=new BufferedWriter(new FileWriter(path)); bw.write("测试BufferedWriter"); bw.flush(); BufferedReader br=new BufferedReader(new FileReader(path)); char[] arr=new char[1024]; int len; while ((len=br.read(arr))!=-1){ System.out.println(new String(arr)); } bw.close(); br.close(); } /* * 一次读取一行,字符缓存流的特有功能 * */ public void buffedTest1() throws IOException { String path="E:\\Java\\00_0\\4.txt"; BufferedWriter bw=new BufferedWriter(new FileWriter(path,true)); bw.write("测试BufferedWriter"); bw.newLine(); bw.write("测试BufferedWriter"); bw.flush(); BufferedReader br=new BufferedReader(new FileReader(path)); char[] arr=new char[1024]; String line ; while ((line=br.readLine())!=null){ System.out.println(line); } bw.close(); br.close(); } public void buffedTest2() throws IOException { String path="E:\\Java\\00_0\\4.txt"; BufferedWriter bw=new BufferedWriter(new FileWriter(path,true)); bw.newLine(); bw.write("测试BufferedWriter"); bw.flush(); BufferedReader br=new BufferedReader(new FileReader(path)); int c; while ((c=br.read())!=-1){ System.out.print((char)c); } bw.close(); br.close(); }