日常開發中,我們反覆造輪子的場景其實有限。整理 20 個高頻、可直接落地的代碼片段,涵蓋字串、IO、日期、網絡、加密、PDF、郵件等核心領域,建議收藏備查。
String s = String.valueOf(123); // int → String
int i = Integer.parseInt("123"); // String → int
try (BufferedWriter w = new BufferedWriter(
new FileWriter("log.txt", true))) {
w.write("new line");
w.newLine();
}
String method = new Object(){}.getClass()
.getEnclosingMethod().getName();
LocalDate date = LocalDate.parse("2024-06-15");
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String formatted = date.format(fmt);
// 建議生產環境使用 HikariCP
HikariConfig cfg = new HikariConfig();
cfg.setJdbcUrl("jdbc:oracle:thin:@//host:1521/service");
cfg.setUsername("user"); cfg.setPassword("pwd");
DataSource ds = new HikariDataSource(cfg);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
Files.copy(srcPath, dstPath,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
BufferedImage thumb = Thumbnails.of(srcFile)
.size(200, 200)
.outputQuality(0.8)
.asBufferedImage();
ImageIO.write(thumb, "jpg", dstFile);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);
MyDto dto = mapper.readValue(json, MyDto.class);
PdfWriter writer = new PdfWriter("out.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document doc = new Document(pdf);
doc.add(new Paragraph("Hello PDF").setFontSize(14));
doc.close();
System.setProperty("http.proxyHost", "proxy.com");
System.setProperty("http.proxyPort", "8080");
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "pass".toCharArray());
}
});
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}
Robot robot = new Robot();
Rectangle rect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage img = robot.createScreenCapture(rect);
ImageIO.write(img, "png", new File("screen.png"));
Files.list(dirPath)
.filter(p -> p.toString().endsWith(".java"))
.forEach(System.out::println);
try (ZipOutputStream zos = new ZipOutputStream(
new FileOutputStream("archive.zip"))) {
Files.walk(srcDir)
.filter(p -> !Files.isDirectory(p))
.forEach(p -> {
zos.putNextEntry(new ZipEntry(srcDir.relativize(p).toString()));
Files.copy(p, zos);
zos.closeEntry();
});
}
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(new File("data.xml"));
NodeList users = doc.getElementsByTagName("user");
String[][] data = {{"k1","v1"},{"k2","v2"}};
Map map = Arrays.stream(data)
.collect(Collectors.toMap(a -> a[0], a -> a[1]));
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, to);
msg.setSubject(subject);
msg.setText(content);
Transport.send(msg);
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com"))
.GET().build();
String resp = client.send(req, BodyHandlers.ofString()).body();
int[] arr = {1,2,3};
arr = Arrays.copyOf(arr, 5); // {1,2,3,0,0}
try-with-resources