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

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

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

至关于对文件内容作了一次增删改查。app

①刚开始是这样写的工具

/*
 * 读取文件内容
 */
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中文占几个字节spa

②修改是这样
.net

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

相关文章
相关标签/搜索