Java文件读写操作
来源:互联网 发布:农家乐商机数据 编辑:程序博客网 时间:2024/05/21 11:37
Java 文件读写操作
package fileopt;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.RandomAccessFile;/** * 修改文件 */public class FileModify { /** * 读取文件内容 * * @param filePath * @return */ public String read(String filePath) { BufferedReader br = null; String line = null; StringBuffer buf = new StringBuffer(); try { // 根据文件路径创建缓冲输入流 br = new BufferedReader(new FileReader(filePath)); // 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中 while ((line = br.readLine()) != null) { // 此处根据实际需要修改某些行的内容 if (line.startsWith("a")) { buf.append(line).append(" start with a"); } else if (line.startsWith("b")) { buf.append(line).append(" start with b"); } // 如果不用修改, 则按原来的内容回写 else { buf.append(line); } buf.append(System.getProperty("line.separator")); } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭流 if (br != null) { try { br.close(); } catch (IOException e) { br = null; } } } return buf.toString(); } /** * 将内容回写到文件中 * * @param filePath * @param content */ public void write(String filePath, String content) { BufferedWriter bw = null; try { // 根据文件路径创建缓冲输出流 bw = new BufferedWriter(new FileWriter(filePath)); // 将内容写入文件中 bw.write(content); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭流 if (bw != null) { try { bw.close(); } catch (IOException e) { bw = null; } } } } public void fileAppender(String fileName,String content) throws IOException{ BufferedReader reader = new BufferedReader(new FileReader(fileName)); String line = null; // 一行一行的读 StringBuilder sb = new StringBuilder(); sb.append(content); while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\r\n"); } reader.close(); //写回去 RandomAccessFile mm = new RandomAccessFile(fileName, "rw"); mm.writeBytes(sb.toString()); mm.close(); } /** * 主方法 */ public static void main(String[] args) { String filePath = FileModify.class.getResource("").getPath()+"test.properties"; // 文件路径 FileModify obj = new FileModify(); obj.write(filePath, obj.read(filePath)); // 读取修改文件 try { obj.fileAppender(filePath, "set a=b \n"); } catch (IOException e) { e.printStackTrace(); } }}
0 0
- java 读写文件操作
- java读写文件操作
- Java文件读写操作
- JAVA读写文件操作
- java文件读写操作
- Java文件读写操作
- java文件读写操作
- java 文件读写 操作
- java 文件读写操作
- JAVA读写文件操作
- java文件读写操作
- 文件读写操作-Java
- Java --- 读写文件操作
- Java文件读写操作
- Java文件读写操作
- Java文件读写操作
- java文件读写操作
- Java文件读写操作
- 串口通信Usart发送程序
- Construct 2 制作游戏心得
- 由于 box.style.left只能获取行内样式的值,不能获取到css中JS中样式left等值;用JS获取外部CSS样式--currentStyle和getComputedStyle的兼容写法
- Orm之XML解析
- Android中Activity和Fragment之间的通信
- Java文件读写操作
- 剑指Offer 9题 斐波那契数列(Fibonacci) Java版
- 去除CSDN 博客页广告的历程
- JS中各种宽度距离小结
- [数据库连接池] Java数据库连接池--DBCP浅析.
- Chrome“无法添加来自此网站的应用”的解决办法
- [HDU]5531 Rebuild (三分法求下凸函数,维护最小圆面积)
- 两个辅助指针变量挖字符串(4种实现方式)
- C/C++野指针