標籤:file pre pen sch get tostring day 字元 執行
在項目中經常會用到定時器,在筆試或者面試中也會經常問到定時器和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秒執行一次。
java定時讀取檔案