日常 Java 開發中,我們反覆編寫許多通用邏輯:日期格式化、集合轉換、檔案讀寫、加密雜湊、JSON 序列化、反射操作等。本文精選 20 個高頻、生產級的程式碼片段,涵蓋字串處理、集合操作、日期時間、IO 流、加密、JSON、反射、執行緒、驗證、日誌十大場景,可直接複製整合至專案工具類,並附上關鍵注意事項與現代 API 替代建議(Java 8+ Stream、Optional、java.time、NIO.2)。
public class StringUtils {
public static boolean isBlank(CharSequence cs) {
return cs == null || cs.toString().trim().isEmpty();
}
public static String join(CharSequence delimiter, CharSequence... elements) {
if (elements == null) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < elements.length; i++) {
if (i > 0) sb.append(delimiter);
if (elements[i] != null) sb.append(elements[i]);
}
return sb.toString();
}
// Java 8+ 建議:String.join(",", list) / Stream.collect(Collectors.joining(","))
}
public static List distinctPreserveOrder(List list) {
if (list == null) return Collections.emptyList();
return list.stream().distinct().collect(Collectors.toCollection(LinkedList::new));
// 或 Java 8 前:new ArrayList<>(new LinkedHashSet<>(list))
}
public class DateUtils {
private static final DateTimeFormatter DEFAULT_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static String format(LocalDateTime dt, String pattern) {
return dt == null ? "" : dt.format(DateTimeFormatter.ofPattern(pattern));
}
public static LocalDateTime parse(String str, String pattern) {
return str == null ? null : LocalDateTime.parse(str, DateTimeFormatter.ofPattern(pattern));
}
public static long betweenDays(LocalDate start, LocalDate end) {
return ChronoUnit.DAYS.between(start, end);
}
// 避免使用已過時的 SimpleDateFormat(非執行緒安全),改用 DateTimeFormatter(不可變、執行緒安全)
}
public class FileUtils {
public static String readFileToString(Path path, Charset charset) throws IOException {
return Files.readString(path, charset); // Java 11+
// Java 8: new String(Files.readAllBytes(path), charset)
}
public static void writeStringToFile(Path path, String content, Charset charset, OpenOption... options) throws IOException {
Files.writeString(path, content, charset, options); // Java 11+
// Java 8: Files.write(path, content.getBytes(charset), options)
}
public static void copyDirectory(Path source, Path target) throws IOException {
Files.walkFileTree(source, new SimpleFileVisitor() {
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Files.createDirectories(target.resolve(source.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
});
}
}
public class JsonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper()
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 忽略 null 欄位
public static String toJson(Object obj) {
try { return MAPPER.writeValueAsString(obj); }
catch (JsonProcessingException e) { throw new RuntimeException(e); }
}
public static T fromJson(String json, Class clazz) {
try { return MAPPER.readValue(json, clazz); }
catch (IOException e) { throw new RuntimeException(e); }
}
// 針對泛型:MAPPER.readValue(json, new TypeReference>(){})
}
所有 20 個片段的完整實作、單元測試(JUnit 5)、Maven 依賴配置已開源:
https://github.com/your-repo/java-snippets-20
掌握這 20 類高頻片段,能讓你在日常開發中少寫樣板碼、避開常見坑、專注業務邏輯,顯著提升編碼效率與程式碼品質。