读写文件流指定编码方式

1.import java.io.BufferedReader;   
2.import java.io.BufferedWriter;   
3.import java.io.DataInputStream;   
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 FileUtil {   
11.    public static void createFile(String file, String content, String encodType)   
12.            throws IOException {   
13.        FileOutputStream writerStream = new FileOutputStream(file);   
14.        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(   
15.                writerStream, encodType));   
16.        writer.write(content);   
17.        writer.close();   
18.    }   
19.  
20.    public static String getContent(String file, String encodType)   
21.            throws IOException {   
22.        //"xx\r\n" read -> "xx"   
23.        StringBuffer content = new StringBuffer();   
24.        FileInputStream fis = new FileInputStream(file);   
25.        DataInputStream dis = new DataInputStream(fis);   
26.        BufferedReader br = new BufferedReader(new InputStreamReader(dis,   
27.                encodType));   
28.        String line = null;   
29.        if((line = br.readLine()) != null){   
30.            content.append(line);   
31.        }   
32.        while ((line = br.readLine()) != null) {   
33.            content.append("\r\n" + line);   
34.        }   
35.        br.close();   
36.        dis.close();   
37.        fis.close();   
38.        return content.toString();   
39.    }   
40.  
41.    public static void main(String[] args) throws IOException {   
42.         String s = "耦嬡沵哋 尒尒婀焱暒妏恻鉽嗵過";   
43.         createFile("c:/cnt1.txt", s, "UTF-8");   
44.         createFile("c:/cnt2.txt", s, "GBK");   
45.         String con1 = getContent("c:/cnt1.txt", "UTF-8");   
46.         System.out.println(con1);   
47.         String con2 = getContent("c:/cnt2.txt", "GBK");   
48.         System.out.println(con2);   
49.    }   
50.}  

你可能感兴趣的:(java,C++,c,C#)