2 babbma babbma 于 2014.03.10 09:34 提问

在java类timetask中不能删除文件,只能读写,请各位大侠看看

package common;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import send.service.TimeTask;

public class P6Main {

public static void main(String[] args) {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    TimerThread1 t1 = new TimerThread1();
    pool.execute(t1);
    pool.shutdown();
}

}

class TimerThread1 extends Thread {
@Override
public void run() {
try {
// long time1 = Long.parseLong(FileCommon
// .getSystemConfigProperties("TIMEOUT"));
TimeTask.getTimer1(1);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

package send.service;

import java.io.File;
import java.io.IOException;
import java.util.Timer;

public class TimeTask {
public static void getTimer1(long time1) {
Timer timer = new Timer();
timer.schedule(new INXMLTask(), 1000, time1 * 60 * 1000);
}

static class INXMLTask extends java.util.TimerTask {
    @Override
    public void run() {
        try {
            String dir = "c:\\beifen\\";
            File file = new File(dir);
            File[] files = file.listFiles();
            for(int i = 0 ;i < files.length;i ++){
                if(files[i].exists()){
                    files[i].deleteOnExit();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

}

1个回答

flyingstarwb
flyingstarwb   2014.03.14 13:29

Timer其实内部只有一个线程,所以你用files[i].deleteOnExit();删除文件必须等到线程结束才能删除,你需要使用delete方法删除文件。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!