字串與基本型別轉換
// 1. int ↔ String
String s = String.valueOf(42); // "42"
int i = Integer.parseInt("42"); // 42
// 2. 追加寫入檔案
try (BufferedWriter bw = new BufferedWriter(new FileWriter("log.txt", true))) {
bw.write("新內容");
bw.newLine();
}
// 3. 取得當前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
// 4. 字串解析日期
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2024-01-15");
// Java 8+ 推薦
LocalDate ld = LocalDate.parse("2024-01-15");
LocalDateTime ldt = LocalDateTime.parse("2024-01-15T10:30:00");
JDBC 與日期處理
// 5. JDBC 連線 Oracle (屬性檔配置)
Properties props = new Properties();
props.load(new FileInputStream("db.properties"));
Connection conn = DriverManager.getConnection(
props.getProperty("url"), props.getProperty("user"), props.getProperty("pwd"));
// 6. util.Date ↔ sql.Date
java.util.Date uDate = new java.util.Date();
java.sql.Date sDate = new java.sql.Date(uDate.getTime());
// 反向
java.util.Date u2 = new java.util.Date(sDate.getTime());
NIO 高效檔案操作
// 7. NIO 檔案複製 (大檔案分塊傳輸)
public static void copy(File src, File dest) throws IOException {
try (FileChannel in = FileChannel.open(src.toPath(), StandardOpenOption.READ);
FileChannel out = FileChannel.open(dest.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
long size = in.size();
long pos = 0;
final long CHUNK = 64 * 1024 * 1024 - 32 * 1024; // 64MB - 32KB
while (pos < size) pos += in.transferTo(pos, Math.min(CHUNK, size - pos), out);
}
}
// 8. 圖片縮略圖生成
Thumbnails.of(srcFile).size(200, 200).outputQuality(0.8).toFile(destFile); // Thumbnailator 庫
JSON 處理
// 9. JSONObject 建構 (org.json)
JSONObject json = new JSONObject();
json.put("city", "Taipei");
json.put("country", "Taiwan");
String output = json.toString(); // {"city":"Taipei","country":"Taiwan"}
// 10. Jackson 物件序列化 (推薦生產環境)
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(userObject);
User user = mapper.readValue(jsonStr, User.class);
集合與 Stream (Java 8+)
// 11. List 去重
List unique = list.stream().distinct().collect(Collectors.toList());
// 12. 分組統計
Map countByCity = users.stream()
.collect(Collectors.groupingBy(User::getCity, Collectors.counting()));
// 13. 分區
Map> byAdult = users.stream()
.collect(Collectors.partitioningBy(u -> u.getAge() >= 18));
// 14. 扁平化
List allTags = articles.stream()
.flatMap(a -> a.getTags().stream())
.collect(Collectors.toList());
檔案與資源處理
// 15. 讀取 classpath 資源
InputStream is = MyClass.class.getResourceAsStream("/config.properties");
// 16. 暫存檔案
File tmp = File.createTempFile("prefix-", ".tmp");
tmp.deleteOnExit();
// 17. 目錄遍歷 (Java 7+)
Files.walk(Paths.get("/data")).filter(Files::isRegularFile).forEach(System.out::println);
加密與編碼
// 18. Base64 編解碼 (Java 8+)
String encoded = Base64.getEncoder().encodeToString("密文".getBytes(StandardCharsets.UTF_8));
String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
// 19. MD5 摘要
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));
String hex = bytesToHex(digest); // 需自行實現或用 Hex.encodeHexString (Commons Codec)
實用工具方法
// 20. 安全關閉資源 (Java 7+ try-with-resources 模式)
public static void closeQuietly(AutoCloseable... resources) {
for (AutoCloseable r : resources) {
if (r != null) try { r.close(); } catch (Exception ignored) {}
}
}
使用建議
- 優先使用標準庫 (java.nio, java.time, java.util.stream)
- JSON 處理生產環境首選 Jackson/Gson
- 檔案/網路操作務必
try-with-resources
- 日期時間一律用
java.time 套件 (Java 8+)
- 常用片段收錄至團隊共享 Snippet 庫 (IDE Live Templates / GitHub Gist)