`
java-mans
  • 浏览: 11435172 次
文章分类
社区版块
存档分类
最新评论

按编码格式读写文件

 
阅读更多

package com.hpli.demo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class FileUtil {

/**
* 根据编码集创建
* @param file
* @param content
* @param encodType
* @throws IOException
*/
public static void createFile(String file, String content, String encodType)
throws IOException {
FileOutputStream writerStream = new FileOutputStream(file);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
writerStream, encodType));
writer.write(content);
writer.close();
}

/**
* 读取文件内容
* @param file
* @param encodType
* @return
* @throws IOException
*/
public static String getContent(String file, String encodType)
throws IOException {
//"xx\r\n" read -> "xx"
StringBuffer content = new StringBuffer();
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis,
encodType));
String line = null;
if((line = br.readLine()) != null){
content.append(line);
}
while ((line = br.readLine()) != null) {
content.append("\r\n" + line);
}
br.close();
dis.close();
fis.close();
return content.toString();
}

public static void main(String[] args) throws IOException {
String str = "耦嬡沵哋 尒尒婀焱暒妏恻鉽嗵過";
createFile("F:/cnt1.txt", str, "UTF-8");
createFile("F:/cnt2.txt", str, "GBK");
String con1 = getContent("F:/cnt1.txt", "UTF-8");
System.out.println(con1);
String con2 = getContent("F:/cnt2.txt", "GBK");
System.out.println(con2);
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics