您的位置:首页 > 其它

IO操作,对文件内容进行读取和写入

2015-11-18 09:27 761 查看
从一个文件中获取内容,显示在页面上,并可以进行编辑。
点击保存后再将页面上的内容写入到文件中。
相当于对文件内容做了一次增删改查。
①刚开始是这样写的
/*
* 读取文件内容
*/
public String readFileMethod(String path) throws IOException {
File file = new File(path);
if (!file.exists() || file.isDirectory())
throw new FileNotFoundException();
FileInputStream fis = new FileInputStream(file);
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
while ((fis.read(buf)) != -1) {
sb.append(new String(buf, "UTF-8"));// 防止中文乱码
buf = new byte[1024];// 重新生成,避免和上次读取的数据重复
}
return sb.toString();
}

/*
* 写数据到文件
*/
public AjaxMsg writeFileMethod(String path, String arrCity) {
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file, false);
StringBuffer sb = new StringBuffer();
sb.append(arrCity);
out.write(sb.toString().getBytes("utf-8"));
out.close();
return new AjaxMsg(true, "保存文件成功!");
} catch (Exception e) {
e.printStackTrace();
return new AjaxMsg(false, "保存文件失败!");
}
}

但是这样的效果是,个别中文出现乱码。原因是UTF-8字符大部分占用的是三个字节,而读取文件的时候是每次取1024个字节,导致出现乱码。

具体见:字符编码的演变:UTF-8中文占几个字节

②修改是这样

/*
* 读取文件内容
*/
public String readFileMethod(String path) throws IOException {
File file = new File(path);
if (!file.exists() || file.isDirectory())
throw new FileNotFoundException();
String arrCity_value = FileUtils.readFileToString(file, "UTF-8");
return arrCity_value;
}

/*
* 写数据到文件
*/
public AjaxMsg writeFileMethod(String path, String arrCity) {
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileUtils.write(file, arrCity, "UTF-8");
return new AjaxMsg(true, "保存文件成功!");
} catch (Exception e) {
e.printStackTrace();
return new AjaxMsg(false, "保存文件失败!");
}
}

这次用的是 org.apache.commons.io.FileUtils 工具类中的方法,直接调用即可,非常方便。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  FileUtils