读写文件的编码格式需要保持一致,否则可能会出现中文乱码问题。以下使用UTF-8编码方式写入和读取文件。
1.写入txt文件
//--------------写入文本-------------//
String fpname="d:/txt/1.txt";
String vcontent="";
BufferedWriter bw=null;
try {
//自动创建目录
File file = new File(fpname);
File file_dir = new File(file.getParent());
if(!file_dir.exists()){
file_dir.mkdirs();
}
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osr = new OutputStreamWriter(fos,"UTF-8");//避免中文乱码
bw = new BufferedWriter(osr);
int n=0;
//list为要写入的数据队列
List<HashMap<String, Object>> list=rMsg.getList();
//遍历list向文件逐行写入
for (HashMap<String, Object> itMap : list) {
//序号|用户编号|用户名称|
n+=1;
vcontent=String.valueOf(n);
vcontent+="|";
vcontent+=Comm.getString(itMap.get("arch_no"));
vcontent+="|";
vcontent+=Comm.getString(itMap.get("user_name"));
vcontent+="|";
bw.write(vcontent);
bw.newLine();
}
bw.flush();
}finally {
try {
if (bw!=null){
bw.close();
}
}catch (Exception e) {
logger.error(estr+"读写失败."+ e.toString());
}
}
2.读取txt文件
读取txt文件时,文件编码是utf-8,如果没有设置编码格式,程序默认使用系统的编码GBK,有可能会中文乱码。
需要在建立输入流的时候使用与原文件一致的编码格式读取,避免出现中文乱码问题。
//--------------读取文本-------------//
String fpath="d:/1.txt";
BufferedReader br=null;
try {
File file = new File(fpath);
if(!file.exists()){
rMsg.setResultMsg("文件不存在.");
return rMsg;
}
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//避免中文乱码
br = new BufferedReader(isr);
List<String> list = new ArrayList<String>();
String str_line="";
//逐行读取文本
while ((str_line=br.readLine())!=null){
list.add(str_line);
}
//读取文件并执行业务
//.... list
}finally {
try {
if (br!=null){
br.close();
}
}catch (Exception e) {
logger.error(estr+"关闭文件失败."+ e.toString());
}
}