读写文件流指定编码方式

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.}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值