java 替换文件内容

java 替换文件内容,第1张

代码如兆敏汪下:

/***

* 方法:

* @Title: replaceContentToFile

* @Description: TODO

* @param @param path 文件

* @param @param str 开始删除的字符

* @param @param con 追加的族仔文本

* @return void返回拿镇类型

* @throws

*/

public static void replaceContentToFile(String path, String str ,String con){

try {

FileReader read = new FileReader(path)

BufferedReader br = new BufferedReader(read)

StringBuilder content = new StringBuilder()

while(br.ready() != false){

content.append(br.readLine())

content.append("\r\n")

}

System.out.println(content.toString())

int dex = content.indexOf(str)

if( dex != -1){

System.out.println(content.substring(dex, content.length()))

content.delete(dex, content.length())

}

content.append(con)

br.close()

read.close()

FileOutputStream fs = new FileOutputStream(path)

fs.write(content.toString().getBytes())

fs.close()

} catch (FileNotFoundException e) {

e.printStackTrace()

} catch (IOException e){

e.printStackTrace()

}

}

那不就是将1.txt中的内容写入2.txt中吗?

import java.io.FileNotFoundException

import java.io.FileReader

import java.io.FileWriter

import java.io.IOException

public class TxtReplace {

public static void main(String[] args) {

FileReader fr = null

FileWriter fw = null

int b = 0

char[] cbuf = new char[18]

try {

fr = new FileReader("E:\\1.txt")//1.txt保存的位置

fw = new FileWriter("E:\\2.txt")//2.txt保存的位置

while ((b=fr.read(cbuf,0,18))!=-1)

{fw.write(cbuf,0,18)

}

}

catch(FileNotFoundException e){

e.getMessage()

e.printStackTrace()

}

catch(IOException e)

{ e.getMessage()

e.printStackTrace()

}

finally {

try {

fr.close()

fw.close()

} catch(IOException e){

e.getMessage()

e.printStackTrace()

}

}

}

}

两点:

1.map = new HashMap<String, String>()

这洞樱句 应该改为 map = new WeekHashMap<String,String>()

否则会报悄颤哪java.lang.OutOfMemoryError: Java heap space这个错误。

2. public FileWriter (File file, boolean append) append如果是true那么这个文件会把后面写的内容添加启码到file文件里。这是一种追加模式。如果为假,则替换原先内容


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12202053.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存