在网上查了很多关于修改文件的方法,不得其要领。自己想了两个取巧的办法,来解决对文件的修改。一:读取一个文件file1(FileReader and BufferedReader),进行操作后写入file2(FileWriter and BufferedWriter),然后删除file1,更改file2文件名为file1(Rename()方法)。二:创建字符缓冲流(StringBuffer),读取文件内容赋给字符缓冲流,再将字符缓冲流中的内容写入到读取的文件中。例如: test.txt 这里是放在d盘的根目录下,内容如下 able adj 有才干的,能干的 active adj 主动的,活跃的 adaptable adj 适应性强的 adroit adj 灵巧的,机敏的 运行结果生成在同目录的 test1.txt中 able #adj*有才干的,能干的 active #adj*主动的,活跃的 adaptable #adj*适应性强的 adroit #adj*灵巧的,机敏的 代码: public class Test { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new FileReader("D://test.txt")); StringBuffer sb = new StringBuffer(); String lineContent = null ;while( (lineContent = br.readLine()) != null){ String[] sp = lineContent.split(" ");sp[0] = sp[0].concat(" *");sp[1] = sp[1].concat("# ");for(int i=0;i sb.append(sp[i]);}sb.append("/r/n");}FileWriter fw = new FileWriter("D://test2.txt"); fw.write(sb.toString()); br.close(); fw.close(); }}
JAVA同时读写文件
最新推荐文章于 2023-07-09 18:12:57 发布