Java 不仅是非常强大的应用开发语言,更是自动化的利器。本文分享10个能让你事半功倍的 Java 脚本,助你一臂之力,提高工作效率。
1.文件重复查找器
存储空间不足?重复文件可能是罪魁祸首。这里有一个 Java 脚本,用于识别和删除那些烦人的重复文件:
import java.io.*;
import java.nio.file.*;
import java.security.*;
import java.util.*;
publicclass DuplicateFileFinder {
public static String hashFile(Path file) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(file)) {
byte[] buffer = newbyte[8192];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
}
byte[] digest = md.digest();
return Base64.getEncoder().encodeToString(digest);
}
public static void findDuplicates(String directory) throws Exception {
Map<String, List<Path>> hashes = new HashMap<>();
Files.walk(Paths.get(directory)).filter(Files::isRegularFile).forEach(path -> {
try {
String hash = hashFile(path);
hashes.computeIfAbsent(hash, k -> new ArrayList<>()).add(path);
} catch (Exception ignored) {}
});
hashes.values().stream().filter(list -> list.size() > 1).forEach(list -> {
System.out.println("Duplicate files: " + list);
});
}
}
2.自动文件整理器
如果你的下载文件夹乱七八糟,这个脚本可以帮助按文件类型进行整理,将文档、图片等放入不同的文件夹。
import java.io.File;
import java.nio.file.*;
publicclass FileOrganizer {
public static void organizeDirectory(String directory) {
File folder = new File(directory);
for (File file : folder.listFiles()) {
if (file.isFile()) {
String extension = getExtension(file.getName());
Path targetDir = Paths.get(directory, extension.toUpperCase());
try {
Files.createDirectories(targetDir);
Files.move(file.toPath(), targetDir.resolve(file.getName()), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
System.out.println("Error moving file: " + file.getName());
}
}
}
}
private static String getExtension(String filename) {
int lastIndex = filename.lastIndexOf('.');
return (lastIndex == -1) ? "Unknown" : filename.substring(lastIndex + 1);
}
}
3.每日备份系统
安排一个 Java 脚本,每天自动备份重要文件到指定位置。设置好文件路径,让它自动运行!
import java.io.*;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.Date;
publicclass DailyBackup {
public static void backupDirectory(String sourceDir, String backupDir) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String today = sdf.format(new Date());
Path backupPath = Paths.get(backupDir, "backup-" + today);
Files.createDirectories(backupPath);
Files.walk(Paths.get(sourceDir)).forEach(source -> {
try {
Path destination = backupPath.resolve(Paths.get(sourceDir).relativize(source));
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println("Error backing up file: " + source);
}
});
}
}
4.数据库清理
使用此脚本定期清除旧记录或不必要的数据。设置按计划删除过时的条目,以保持数据库优化。
import java.sql.*;
public class DatabaseCleanup {
public static void cleanupDatabase(String jdbcUrl, String user, String password) {
String sql = "DELETE FROM your_table WHERE your_column < DATE_SUB(NOW(), INTERVAL 30 DAY)";
try (Connection conn = DriverManager.getConnection(jdbcUrl, user, password);
Statement stmt = conn.createStatement()) {
int rowsDeleted = stmt.executeUpdate(sql);
System.out.println("Deleted " + rowsDeleted + " old records.");
} catch (SQLException e) {
System.out.println("Database cleanup failed.");
}
}
}
5.邮件自动化
如果需要定期发送报告,这个 Java 脚本与 SMTP 服务器集成,实现电子邮件的自动发送,节省时间。
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
publicclass EmailAutomation {
public static void sendEmail(String recipient, String subject, String body) {
String senderEmail = "your-email@example.com";
String senderPassword = "your-password";
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.example.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
returnnew PasswordAuthentication(senderEmail, senderPassword);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
System.out.println("Email sent successfully");
} catch (MessagingException e) {
System.out.println("Failed to send email");
}
}
}
6.网站状态检查器
若需要监控网站的正常运行时间,这个脚本可以实现定期向你的网站发送请求,并在网站宕机时通知到你。
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
publicclass WebsiteChecker {
public static void checkWebsite(String siteUrl) {
try {
URL url = new URL(siteUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
System.out.println(siteUrl + " is up and running!");
} else {
System.out.println(siteUrl + " is down. Response code: " + responseCode);
}
} catch (IOException e) {
System.out.println("Could not connect to " + siteUrl);
}
}
}
7.天气查询器
集成天气 API,在终端获取每日天气预报。可以根据位置定制特定更新。
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
publicclass WeatherRetriever {
public static void getWeather(String apiUrl) {
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream responseStream = connection.getInputStream();
Scanner scanner = new Scanner(responseStream);
StringBuilder response = new StringBuilder();
while (scanner.hasNext()) {
response.append(scanner.nextLine());
}
System.out.println(response.toString());
scanner.close();
} catch (IOException e) {
System.out.println("Failed to retrieve weather data.");
}
}
}
8.自动密码生成器
使用此脚本生成安全、随机的密码。你可以指定长度、复杂性,甚至批量输出密码列表。
import java.security.SecureRandom;
publicclass PasswordGenerator {
privatestaticfinal String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%&*";
public static String generatePassword(int length) {
SecureRandom random = new SecureRandom();
StringBuilder password = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int index = random.nextInt(CHARACTERS.length());
password.append(CHARACTERS.charAt(index));
}
return password.toString();
}
}
9.PDF 文件合并器
处理 PDF 文档时,这个 Java 脚本将多个 PDF 文件合并为一个,使文件管理更简单。
import java.io.*;
import java.util.*;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
publicclass PDFMerger {
public static void mergePDFs(List<String> pdfPaths, String outputFilePath) throws IOException {
PDFMergerUtility merger = new PDFMergerUtility();
for (String pdfPath : pdfPaths) {
merger.addSource(pdfPath);
}
merger.setDestinationFileName(outputFilePath);
merger.mergeDocuments(null);
System.out.println("PDFs merged into: " + outputFilePath);
}
}
10.屏幕截图捕获器
程序化地捕获屏幕截图。使用它来创建屏幕快照或自动化需要视觉文档的工作流程。
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
publicclass ScreenCapture {
public static void takeScreenshot(String savePath) {
try {
Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenShot = robot.createScreenCapture(screenRect);
ImageIO.write(screenShot, "png", new File(savePath));
System.out.println("Screenshot saved to " + savePath);
} catch (Exception e) {
System.out.println("Failed to take screenshot.");
}
}
}