首页 > 其他 > 详细

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

时间:2015-11-18 10:53:06      阅读:310      评论:0      收藏:0      [点我收藏+]

从一个文件中获取内容,显示在页面上,并可以进行编辑。

点击保存后再将页面上的内容写入到文件中。

相当于对文件内容做了一次增删改查。

①刚开始是这样写的

/*
 * 读取文件内容
 */
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 工具类中的方法,直接调用即可,非常方便。

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

原文:http://my.oschina.net/chinamummy29/blog/531828

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!