import java.io.FileWriter; import java.io.IOException; public class Demo01 { //直接写入utf-8编码文件中是乱码 public static void main(String[] args) throws IOException { FileWriter fw=new FileWriter("E:\java\utf-8.txt",true); fw.write("你好,小猪佩奇"); fw.close(); } } OutputStreamWriter类
写入utf-8编码文件 import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class Demo02 { //转换流写入utf-8编码文件中显示就正常了 public static void main(String[] args) throws IOException { //指定目的地 FileOutputStream fos=new FileOutputStream("E:\java\utf-8.txt",true); //创建转换流 OutputStreamWriter osw=new OutputStreamWriter(fos, "utf-8"); //写入内容 osw.write("你好"); osw.flush(); //释放资源(new了谁就关谁 先开的后关) osw.close(); fos.close(); } } 写入gbk文件 import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class Demo03 { //写入gbk文件 public static void main(String[] args) throws IOException { //指定目的地 FileOutputStream fos=new FileOutputStream("E:\java\gbk.txt",true); //创建转换流 OutputStreamWriter osw=new OutputStreamWriter(fos);//默认gbk osw.write("你好"); osw.close(); fos.close(); } } InputStreamReader类
读取utf-8文件 import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class Demo04 { //读取utf-8文件 public static void main(String[] args) throws IOException { //指定目的地 FileInputStream fis=new FileInputStream("E:\java\utf-8.txt"); //创建转换流 InputStreamReader isr=new InputStreamReader(fis, "utf-8"); int len=0; while((len=isr.read())!=-1){ System.out.println((char)len); } isr.close(); fis.close(); } } 数组字节读取gbk文件 import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class Demo05 { //数组字节读取文件 public static void main(String[] args) throws IOException { //明确数据源 FileInputStream fis=new FileInputStream("E:\java\gbk.txt"); //创建转换流 InputStreamReader isr=new InputStreamReader(fis);//默认gbk //读取文件 char[] ch=new char[24]; int len=0; while((len=isr.read(ch))!=-1){ System.out.println(new String(ch,0,len)); } isr.close(); fis.close(); } }