//这样会不会好一点(未经测试)
public static void changeFileByTag(String strFileName, String strTagStart,
String strTagEnd, String strContent) {
try {
RandomAccessFile raf = new RandomAccessFile(strFileName, "rw");
synchronized(raf){
byte[] bTemp = new byte[ (int) raf.length()];
raf.read(bTemp);
raf.close();
File fTemp = new File(strFileName);
fTemp.delete();
raf = new RandomAccessFile(strFileName,"rw");
String strTempFile = new String(bTemp);
strTempFile = strTempFile.substring(0,strTempFile.indexOf(strTagStart) +strTagStart.length()) +
strContent + strTempFile.substring(strTempFile.indexOf(strTagEnd));
raf.write(strTempFile.getBytes());
}//End synchronized
raf.close();
}
catch (Exception e) {
e.printStackTrace();
} }
public static void changeFileByTag(String strFileName, String strTagStart,
String strTagEnd, String strContent) {
try {
RandomAccessFile raf = new RandomAccessFile(strFileName, "rw");
synchronized(raf){
byte[] bTemp = new byte[ (int) raf.length()];
raf.read(bTemp);
raf.close();
File fTemp = new File(strFileName);
fTemp.delete();
raf = new RandomAccessFile(strFileName,"rw");
String strTempFile = new String(bTemp);
strTempFile = strTempFile.substring(0,strTempFile.indexOf(strTagStart) +strTagStart.length()) +
strContent + strTempFile.substring(strTempFile.indexOf(strTagEnd));
raf.write(strTempFile.getBytes());
}//End synchronized
raf.close();
}
catch (Exception e) {
e.printStackTrace();
} }
你这样肯定更糟,会导致多个线程都可以同时执行:
RandomAccessFile raf = new RandomAccessFile(strFileName, "rw");
这一句话
FileWriter writer = new FileWriter(strFileName,false);
fTemp.delete();
raf = new RandomAccessFile(strFileName, "rw");
之间加个缓冲吧?
fTemp.delete();把删除文件的命令提交给系统后,文件太大的话可能系统还没执行完删除程序就执行了下面一句了