java定时读取文件

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

public class TimerDemo {
    public static void main(String[] args) throws Exception {
        
        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 = new Timer();
        time.schedule(new TimerTask() {
            public void run() {
                //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 = new BufferedReader(fr);
                    StringBuilder strb = new StringBuilder();
                    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方法中写入自己的代码,我这里主要是用两种方法实现对文件的读取。

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

  

猜你喜欢

转载自www.cnblogs.com/xiangpeng/p/9559476.html