<span style="font-size:14px;">public class MyTask extends TimerTask{
int i=0;
String pathName;
String context;
//创建构造器将要写入的指定txt文件以及写入内容传过来
public MyTask(String pathName,String context) {
this.pathName = pathName;
this.context = context;
}
@Override
public void run() {
OutputStream os = null;
try {
i++;
//将内容写入
os = new FileOutputStream(pathName,true);
os.write((context+i).getBytes());
os.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}</span>
写一个MAIN方法测试一下
public class TimerTest {
public static void main(String[] args) {
String pathName = "f:/test/dd/22.txt";
String context = "加上内容";
Timer timer = new Timer();
//每两秒向指定的txt写入内容
timer.schedule(new MyTask(pathName,context), new Date(), 2000);
}
}