第一个文件 text1.html  第二个文件 text2.html 。在读取text1.html 添加一段内容进去后,写入到text2.html文档中取。判断IO写完后,把text1.html 删除掉,text2.html的名字替换成text1.html。为什么我做的时候无法删除掉文件和替换名字? 

解决方案 »

  1.   

    // 写入文件的内容
             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("删除失败");
    }
      

  2.   

    估计是 流读写完 没有closed()掉吧
      

  3.   


    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")); }
    }
    这个在我这里没出问题
      

  4.   

    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.   

    你这里删了两次。如果确实没删成功,在f1.delete()前做这几个事情:
    is = null;
    Thread.sleep(1000);
    System.gc();
    一次删不掉,可以用循环多做几次。