JAVA从入门到进阶(十二)——IO技术必杀技 转化流中的编码解码

当我们需要按照指定的编码表来读取或写入文件时,就需要用到转换流。
转化流的构造方法中可以按照自定义的编码表来进行编码和解码的工作。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class IOchangedemo3 {
public static void main(String []args) throws IOException
{
	/*
	 * 需求 将文本文件按指定的编码表写入得到文件中
	 * method1()用自带的FileWriter 不能按照指定编码写入
	 * method2()用转换流按UTS-8码表写入
	 * method3()按照FileWriter读取utf-8 读取乱码 因为是按照默认的方式来读取到 乱码数据
	 **/
	method4();
}

private static void method3() throws IOException {
	
	FileReader fr=new FileReader("change2.txt");
	char [] ch= new char[1024];
	int len;
	while((len=fr.read(ch))!=-1)
			{
	System.out.println(new String(ch,0,len));
			}
	
}

private static void method4() throws IOException{
   BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("change2.txt"),"utf-8"));
   char [] ch= new char[1024];
	int len;
	while((len=br.read(ch))!=-1)
			{
	System.out.println(new String(ch,0,len));
			}
}

private static void method2() throws IOException {
	BufferedWriter Bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("change2.txt"),"utf-8"));
	Bw.write("你好");
	Bw.flush();
	Bw.close();
}

private static void method1() throws IOException {
	/*
	 * 其实FileWriter是OutputStreamWriter的子类
	 * 实现了 BufferedWriter Bw =new BufferedWriter(new FileOutputStream("change.txt");
	 * 按照默认的码表进行解析
	 */
	FileWriter  fw=new FileWriter("change.txt");
	fw.write("你好");
	fw.flush();
	fw.close();
}
}

猜你喜欢

转载自blog.csdn.net/weixin_43752167/article/details/87621207
今日推荐