当前位置:编程学习 > JAVA >>

IO删除文本和替换文本名字问题

第一个文件 text1.html  第二个文件 text2.html 。在读取text1.html 添加一段内容进去后,写入到text2.html文档中取。判断IO写完后,把text1.html 删除掉,text2.html的名字替换成text1.html。为什么我做的时候无法删除掉文件和替换名字?  --------------------编程问答-------------------- 贴关键代码吧。 --------------------编程问答-------------------- 除开正常程序原因外,有时也可以考虑一下杀毒软件的影响问题。 --------------------编程问答-------------------- 看看是不是流没关 --------------------编程问答-------------------- 流没关吧   系统会报正在运行或在使用文件受到保护     如果说是那就是流的问题      --------------------编程问答-------------------- // 写入文件的内容
         String metaKey = "<meta name=\"DC.Type\" content=\"" + key + "\">\r\n";

url = treeNode.getUrl();

String strUrl = "E:\\CFG_help\\" + url;// 组合文件路径
String oldStr = "<meta name=\"DC.Type\"";// 包含文件内容
String line = null;
is = new FileInputStream(strUrl);
isr = new InputStreamReader(is, "gbk");
br = new BufferedReader(isr);
FileWriter fw = new FileWriter("c:\\test.html");// 写入的地方
boolean flag = false;
while ((line = br.readLine()) != null) {
   if (line.indexOf("DC.Type") != -1) {
String newStr = line.substring(0,
line.indexOf("content=\"") + 9)+ key + "\">";
fw.write(newStr + "\r\n");
flag = true;
continue;
}
if (line.indexOf("<title>") != -1 && !flag) {
fw.write(metaKey);
flag = true;
continue;
}
fw.write(line + "\r\n");

}
fw.flush();
fw.close();
br.close();
isr.close();
is.close();

if (fw != null) {
File f1 = new File(strUrl);
f1.delete();
System.out.println(f1.delete());
File f2 = new File("c:\\test.html");
f2.renameTo(new File(strUrl));
} else {
System.out.println("删除失败");
} --------------------编程问答-------------------- 估计是 流读写完 没有closed()掉吧 --------------------编程问答--------------------

public class TestReadAndDeleFile {
public static void main(String args[]) throws Exception {

String fileName1 = "d:/temp/text1.txt";
String fileName2 = "d:/temp/text2.txt";
File file1 = new File(fileName1);
File file2 = new File(fileName2);

InputStream is1 = new FileInputStream(file1);
byte[] b = new byte[is1.available()];
is1.read(b);

RandomAccessFile randAccessFile = new RandomAccessFile(file2, "rw");

randAccessFile.seek(randAccessFile.length());
randAccessFile.write(b);

is1.close();
randAccessFile.close();

file1.delete();

file2.renameTo(new File("d:/temp/text3.txt"));

}
}


这个在我这里没出问题 --------------------编程问答-------------------- 一直对IO输入这块比较迷糊,学习了~~ --------------------编程问答--------------------


if (fw != null) {
 File f1 = new File(strUrl);
 f1.delete();
 System.out.println(f1.delete());
 File f2 = new File("c:\\test.html");
 f2.renameTo(new File(strUrl));
 } else {
 System.out.println("删除失败");
 }


注意红色的部分,这里应该打印的是false。因为前面已经将该文件删除,再次删除时无文件。

你最好看看文件磁盘上文件到底被删除和命名没。 --------------------编程问答--------------------
引用 5 楼 fukegogo 的回复:
f1.delete();
System.out.println(f1.delete());

你这里删了两次。

如果确实没删成功,在f1.delete()前做这几个事情:
is = null;
Thread.sleep(1000);
System.gc();
一次删不掉,可以用循环多做几次。
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,