IO操作,对文件内容进行读取和写入
2015-11-18 09:27
761 查看
从一个文件中获取内容,显示在页面上,并可以进行编辑。
点击保存后再将页面上的内容写入到文件中。
相当于对文件内容做了一次增删改查。
①刚开始是这样写的
但是这样的效果是,个别中文出现乱码。原因是UTF-8字符大部分占用的是三个字节,而读取文件的时候是每次取1024个字节,导致出现乱码。
具体见:字符编码的演变:UTF-8中文占几个字节
②修改是这样
这次用的是 org.apache.commons.io.FileUtils 工具类中的方法,直接调用即可,非常方便。
点击保存后再将页面上的内容写入到文件中。
相当于对文件内容做了一次增删改查。
①刚开始是这样写的
/* * 读取文件内容 */ 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 工具类中的方法,直接调用即可,非常方便。
相关文章推荐
- cocos2dx 设置资源寻找路径
- FileUtils 文件工具类org.apache.commons.io.FileUtils
- Cocos2d3.0 制作PList文件
- Commons IO方便读写文件的工具类
- Cocos2d-x3.1FileUtilsTest使用
- [cocos2dx 3.0 (一)] 对文件读写操作 +FileUtils类
- SpringMVC中的文件上传
- Struts2 使用FileUtils上传文件--文件名一定不能有中文!!!
- Java File类总结和FileUtils类
- lua-FileUtils文件工具类
- Android 文件操作帮助类FileUtils文件
- COCOS学习笔记--文件系统
- 使用FileUtils实现一个简易文件下载器
- Apache下的FileUtils.listFiles方法简单使用技巧
- Cocos2d-x ValueMap
- Cocos2d-x 文件管理FileUtils
- java下载文件功能(下载路径可选) 及其文件拷贝方法 (转载)
- 工具类——FileUtils
- 多个文件上传
- springmvc--文件上传