(1)OutputStreamWriter类
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class TransFormatioDemo { public static void main(String[] args) throws IOException { FileOutputStream fos0 = new FileOutputStream("E:\\IO流\\java\\221.txt"); OutputStreamWriter osw0 = new OutputStreamWriter(fos0, "utf-8"); osw0.write("从一种能量形式变成另一种能量形式电能到机械能的转换"); osw0.close(); FileOutputStream fos = new FileOutputStream("E:\\IO流\\java\\121.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");// 系统默认 osw.write("从一种能量形式变成另一种能量形式电能到机械能的转换"); osw.close(); } }
运行后产生的两个文件的文字格式不同。
(2)InputStreamReader类
package pers.zxx.Input; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class InputStreamReaderDemo { public static void main(String[] args) throws IOException { FileInputStream in = new FileInputStream("E:\\IO流\\java\\221.txt"); InputStreamReader isr = new InputStreamReader(in,"utf-8"); int ch = 0; while((ch = isr.read())!=-1){ System.out.print((char)ch); } isr.close(); } }
如果设定的字符格式与编译器的格式不同,会出现乱码的情况。