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

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

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

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

①刚开始是这样写的

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

转载于:https://my.oschina.net/chinamummy29/blog/531828

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值