java---转换流2(InputStreamReader和OutputStreamWriter)

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">★转换流功能2:字符编码转换                          </span>

(1)采用FileWriter以默认方式编码
    FileOutputStream+默认编码表

// 第一种: FileWriter+默认编码表
		FileWriter fw = new FileWriter("files\\w_utf-8.txt");// 该文件的编码由平台(如MyEclipse或dos窗口)定,不一定是utf-8
		fw.write("哈哈哈...");<pre name="code" class="java" style="color: rgb(204, 0, 0);">

 
 

采用转换流以默认方式编码
   OutputStreamWriter + FileOutputStream + 默认编码表

// 第二种: OutputStreamWriter+默认编码表
<pre name="code" class="java">//该文件的编码由平台(如MyEclipse或dos窗口)定,不一定是utf-8
OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream("files\\w_utf-8-1.txt"));

 
 
		os.write("哈哈哈...");
                os.close();

采用转换流以指定编码方式(编码)
   OutputStreamWriter + FileOutputStream +指定编码表

//第三种: OutputStreamWriter+指定编码表
		OutputStreamWriter osw=new  OutputStreamWriter(new FileOutputStream("files\\w_utf-8-2.txt"),"utf-8");
		osw.write("哈哈哈");
		osw.close();
		fw.close();


采用转换流以指定编码方式(解码)
   InputStreamReader + FileInputStream +指定编码表

// InputStreamReader isr=new InputStreamReader(new
		// FileInputStream("files\\gbk.txt"); //如果不指定编码表,则是采用默认的

		// 用转换流自己指定解码表----只要文件的编码表和这里指定的解码表相同,就不会出现乱码
		// InputStreamReader isr=new InputStreamReader(new
		// FileInputStream("files\\gbk.txt") ,"gbk");//ok

		// InputStreamReader isr = new InputStreamReader(new
		// FileInputStream("files\\utf-8.txt"), "gbk");//乱码

		InputStreamReader isr = new InputStreamReader(new FileInputStream(
				"files\\utf-8.txt"), "utf-8");// ok
		char[] cbuf = new char[20];
		int len = isr.read(cbuf);
		String str = new String(cbuf, 0, len);
		System.out.println(str);
		isr.close();






你可能感兴趣的:(java---转换流2(InputStreamReader和OutputStreamWriter))