首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 實用工具方法大全:計時、文件 IO、定時任務、集合操作

     編輯:Java 綜合教學

1. 程序運行計時

long start = System.currentTimeMillis();
// ... 業務邏輯 ...
long end = System.currentTimeMillis();
System.out.println("程序運行時長: " + (end - start) + " ms");

2. 文件讀寫(字符流)

String fileName = "/home/test";
FileWriter writer = null;

public void writeToFile() {
    try {
        writer = new FileWriter(fileName, true); // true = 追加模式
        writer.write("Hello World!");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (writer != null) try { writer.close(); } catch (IOException ignore) {}
    }
}

3. 標誌位(Flag)模式

boolean flag = true;
// ... 業務邏輯 ...
if (condition) {
    // ...
    flag = false; // 根據邏輯修改
} else {
    // ...
}

注意: true/false 語義需明確文檔化,否則邏輯錯誤極難排查。

4. HashMap 鍵值對操作

HashMap<String, String> myMap = new HashMap<>();
// 學號 → 姓名
myMap.put("1", "張三");
myMap.put("2", "李四");
myMap.put("3", "王五");
myMap.put("4", "趙六");

String name = myMap.get("1"); // 返回 "張三"

5. 讀取 CSV 去重存入 List

String path = "/home/allNumber.csv";
public static ArrayList<String> myList = new ArrayList<>();

public static void createList(String path) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(new File(path)));
    String line;
    while ((line = reader.readLine()) != null) {
        if (!myList.contains(line)) { // 去重
            myList.add(line);
        }
    }
    reader.close(); // 必須關閉流
}

優化建議: 大數據量用 HashSet 去重再轉 List,O(1) 查重優於 O(N)。

6. 定時寫文件方案一:ScheduledExecutorService

public class TimedWriter {
    public static void executeFixedRate() throws IOException {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        
        // 參數:任務、首次延遲、間隔、時間單位
        executor.scheduleAtFixedRate(new LogTask(), 0, 5000, TimeUnit.MILLISECONDS);
    }
    
    static class LogTask implements Runnable {
        private String fileName = "/home/test";
        private FileWriter writer = null;
        private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        public void run() {
            try {
                writer = new FileWriter(fileName, true);
                writer.write("Hello World " + df.format(new Date()) + "\n");
                writer.flush(); // 確保寫入磁盤
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) throws Exception {
        executeFixedRate();
        // 主線程不退出,定時任務持續運行
        Thread.currentThread().join();
    }
}

7. 定時寫文件方案二:Timer + Calendar(每日固定時間)

public class DailyTimerWriter {
    private static void executeFixedRate() {
        Timer timer = new Timer();
        Calendar cal = Calendar.getInstance();
        
        // 設置為每日 00:00:00
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        
        Date firstTime = cal.getTime();
        Date now = new Date();
        long interval = firstTime.getTime() - now.getTime();
        
        // 若今日已過,推遲到明天
        if (interval < 0) {
            cal.add(Calendar.DAY_OF_MONTH, 1);
            firstTime = cal.getTime();
            interval = firstTime.getTime() - now.getTime();
        }
        
        // 每 24 小時執行一次
        timer.schedule(new LogTask(), interval, 24 * 60 * 60 * 1000);
    }
    
    static class LogTask extends TimerTask {
        // 同方案一的 run 邏輯
        public void run() { /* 寫文件邏輯 */ }
    }
}

方案對比

特性ScheduledExecutorServiceTimer
線程模型線程池,可多線程單後台線程
異常處理異常不影響後續任務任務拋異常導致 Timer 失效
精度較高較低
推薦場景高併發、長時間運行簡單定時、輕量級

最佳實踐: 生產環境優先使用 ScheduledExecutorService 或 Spring @Scheduled、Quartz 等成熟調度框架。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved