比如test.txt,内容是:
111
222
333
我现在需要把333换成444,333默认是在最后一行,请问各位大佬们怎么才能修改,最好有相关代码,谢谢各位啦
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader(new File("e:/Test/java/test1.txt"));
BufferedReader br = new BufferedReader(fr);
String s;
StringBuilder sb = new StringBuilder();
int i = 0;
//读文件内容
while((s=br.readLine())!=null){
sb.append(s).append("\n");
}
//对内容进行截取去掉最后一个\n,然后截取去掉最后一行,最后加入你想要的内容
System.out.println(sb.substring(0, sb.toString()
.substring(0, sb.length()-1).lastIndexOf("\n"))+"\n4444");
fr.close();
br.close();
}
https://www.cnblogs.com/wasp520/archive/2012/06/29/2570489.html
RandomAccessFile f = null;
try {
f = new RandomAccessFile("E:\saascode\Test\src\cn\test\a.txt","rw");
f.seek(f.length()-1);
f.writeChars("555");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
RandomAccessFile f = null;
try {
f = new RandomAccessFile("E:\saascode\Test\src\cn\test\a.txt","rw");
f.seek(f.length()-1);
f.writeChars("555");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void replaceTxtByStr(String oldStr,String replaceStr,String path) {
String temp = "";
try {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存该行前面的内容
for (int j = 1; (temp = br.readLine()) != null
&& !temp.equals(oldStr); j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
// 将内容插入
buf = buf.append(replaceStr);
// 保存该行后面的内容
while ((temp = br.readLine()) != null) {
buf = buf.append(System.getProperty("line.separator"));
buf = buf.append(temp);
}
br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
还好只是一个破小文件,要怎么玩都可以。你说最后只能替换成555.这里的替换逻辑你自己随便玩。
比如原来有 key=${XXX},你只想替换XXX为 abc,随便找个JAVA stringutils replace即可。。这些还要教 ?