java文件定时读写_java定时读取文件

在项目中经常会用到定时器,在笔试或者面试中也会经常问到定时器和IO流。

public classTimerDemo {public static void main(String[] args) throwsException {

Calendar date=Calendar.getInstance();//设置固定开始时间为 00:00:00

date.set(date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DATE), 0, 0, 0);long daymin = 5000;//5秒

long daySpan = 24 * 60 * 60 * 1000;//一天的秒数,使用这个秒数就能在某天的固定时刻触发定时器//得到定时器实例

Timer time = newTimer();

time.schedule(newTimerTask() {public voidrun() {//run中填写定时器主要执行的代码块//打印当前时间

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

String date1 = df.format(new Date());//new Date()为获取当前系统时间,也可使用当前时间戳

System.err.println(date1);

System.out.println("定时器执行..");//1,字符流读取文件

try{

FileReader fr= new FileReader("E:\\demo.txt");

BufferedReader br= newBufferedReader(fr);

StringBuilder strb= newStringBuilder();while (true) {

String line= null;try{

line=br.readLine();

}catch(IOException e) {

e.printStackTrace();

}if (line == null) {break;

}

strb.append(line);

String result=strb.toString();

System.err.println(result);

}

}catch(FileNotFoundException e) {

e.printStackTrace();

}//2,字节流读取文件

FileInputStream fis = null;try{

fis= new FileInputStream("E:\\demo1.txt");

}catch(FileNotFoundException e1) {

e1.printStackTrace();

}byte[] b = new byte[1024];int len = 0;try{while((len=fis.read(b))!=-1){

System.out.println(new String(b, 0, len));

}

}catch(IOException e) {

e.printStackTrace();

}

}

}, date.getTime(), daymin);//date.getTime()为上面赋值的00:00:00,daymin是执行间隔

};

}

这里主要的代码块为:

Timer time = new Timer();

time.schedule(new TimerTask() {

public void run() {

//run中填写定时器主要执行的代码块

}, date.getTime(), daymin); //date.getTime(),为开始时间,这里获取的是上面赋值的时间;daymin为时间间隔

};

run方法中写入自己的代码,我这里主要是用两种方法实现对文件的读取。

20180830124951360617.png

控制台打印如上,可以看到每5秒执行一次。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值