Java 之 IO操作—— 文本数据的编码和解码

一、解码

  当要读取指定编码的纯文本数据时,可以使用 InputStreamReader 进行解码。所谓解码,即把二进制的字节序列按照指定字符编码解码为可以被正确识别的字符内容。

  Demo:当前系统平台的字符编码方式是:GBK,需要读取一个UTF-8 的文件内容,到当前系统中。

 1 import java.io.BufferedReader;
 2 import java.io.FileInputStream;
 3 import java.io.IOException;
 4 import java.io.InputStreamReader;
 5 
 6 public class TestDecode {
 7 
 8     public static void main(String[] args) {
 9         BufferedReader br = null;
10         try {
11             br = new BufferedReader(new InputStreamReader(new FileInputStream("test_utf8.txt"),"GBK"));
12             
13             String str;
14             while((str = br.readLine())!=null){
15                 System.out.println(str);
16             }
17         } catch (IOException e) {
18             e.printStackTrace();
19         } finally{
20             try {
21                 br.close();
22             } catch (IOException e) {
23             }
24         }
25     }
26 }

二、编码

  要将纯文本数据,按照指定编码转成字节序列时,可以选择 OutputStream。

  Demo:编写程序实现将一个编码为“GBK”的纯文本文件test.txt,复制为编码是“UTF-8”的文件other.txt。

 1 import java.io.BufferedReader;
 2 import java.io.BufferedWriter;
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.InputStreamReader;
 8 import java.io.OutputStreamWriter;
 9 
10 public class TestEncode {
11     public static void main(String[] args) throws IOException {
12         copy(new File("test.txt"),"GBK",new File("other.txt"),"UTF-8");
13     }
14     
15     public static void copy(File src, String srcCharset, File dest, String destCharset) throws IOException{
16         if(!src.isFile()){
17             throw new RuntimeException(src.getPath() + "不存在");
18         }
19         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src),srcCharset));
20         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest),destCharset));
21         
22         String str;
23         while((str = br.readLine())!=null){
24             bw.write(str);
25             bw.newLine();
26         }
27         
28         bw.close();
29         br.close();
30     }
31 }

猜你喜欢

转载自www.cnblogs.com/niujifei/p/12283964.html