建了个文件,进行读写操作后,关闭,然后
aFile.delete()
返回false,文件删除不掉...
再运行一个java程序删它就能删了,是不是读写操作后出了关闭流还得关些其他东西?
网上有解决方法,说加System.gc()或者Thread.sleep(1000),我这都不管用

解决方案 »

  1.   

        File file = new File("temp.text");
        FileWriter writer = new FileWriter(file);
        writer.write("Hello World!\n");
        writer.close();
        System.out.println(file.delete());
        System.out.println(file.exists());
        if(file.exists()){
    file.deleteOnExit();
        }
    结果:
    true
    false
      

  2.   

    系统:Ubuntu 8.04
    JRE: Sun 6u21
      

  3.   

    对,我运行你这个代码结果和你一样,麻烦看看我这代码
    这段代码是从一整个文件传输程序中挑出来的,可能是别的地方影响的,不管怎样我是没辙了private void TaskMerge() {
    File tempFile = null;
    DataInputStream dis = null;
    byte[] dataBuf = new byte[PARTSIZE];
    try {
    RandomAccessFile raf = new RandomAccessFile(ti.getSavePath()
    + ti.getFileName(), "rws");
    for (int i = 1; i <= ti.getFilePartNum(); i++) {
    tempFile = new File(ti.getSavePath() + i + "_"
    + ti.getFileName());
    dis = new DataInputStream(new FileInputStream(tempFile));
    try {
    int len = dis.read(dataBuf, 0, PARTSIZE);
    raf.write(dataBuf, 0, len);
    dis.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    raf.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace(); File aFile = new File("D:\\4_php.zip");
    if (aFile.exists()) {
    boolean bool = aFile.delete();
    System.out.println(bool);

    }
      

  4.   

            File aFile = new File("D:\\4_php.zip");
            if (aFile.exists()) {
                boolean bool = aFile.delete();
                System.out.println(bool);
            } 第一句不会生成一个文件。
      

  5.   

    你给的这些无法得知D:\\4_php.zip有没有关闭啊
      

  6.   

    前边我有对此文件的流操作,最后dis.close()给关闭了啊
      

  7.   

      File aFile = new File("D:\\4_php.zip");
            if (aFile.exists()) {
                boolean bool = aFile.delete();
                System.out.println(bool);
            } 
    这几条语句明明是你抛出IO异常,异常处理中执行的,表明中间处理有问题,你的流关闭没有关闭!
      

  8.   

    dis.close();
    可能并没有正常关闭,抛出异常被最里面的catch块处理掉,然后执行raf.close();
    这句时也无法正常关闭,抛出异常,进入最后一个catch块执行,这样就无法删除那个文件了。
      

  9.   

    关闭流请写在finally块里面,这是必须养成的习惯,习惯好了,很多问题永远不会发生。
      

  10.   

    谢谢各位,问题终于解决了,我前边有个地方确实漏掉一个流关闭。程序一写复杂了就容易出错,怪自己基础不扎实。还有谢谢10楼的提醒,以后会养成finally习惯的~