十個(gè)Java自動(dòng)化腳本,開(kāi)發(fā)效率倍增
Java 不僅是非常強(qiáng)大的應(yīng)用開(kāi)發(fā)語(yǔ)言,更是自動(dòng)化的利器。本文分享10個(gè)能讓你事半功倍的 Java 腳本,助你一臂之力,提高工作效率。
1.文件重復(fù)查找器
存儲(chǔ)空間不足?重復(fù)文件可能是罪魁禍?zhǔn)?。這里有一個(gè) Java 腳本,用于識(shí)別和刪除那些煩人的重復(fù)文件:
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.自動(dòng)文件整理器
如果你的下載文件夾亂七八糟,這個(gè)腳本可以幫助按文件類型進(jìn)行整理,將文檔、圖片等放入不同的文件夾。
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.每日備份系統(tǒng)
安排一個(gè) Java 腳本,每天自動(dòng)備份重要文件到指定位置。設(shè)置好文件路徑,讓它自動(dòng)運(yùn)行!
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.數(shù)據(jù)庫(kù)清理
使用此腳本定期清除舊記錄或不必要的數(shù)據(jù)。設(shè)置按計(jì)劃刪除過(guò)時(shí)的條目,以保持?jǐn)?shù)據(jù)庫(kù)優(yōu)化。
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.郵件自動(dòng)化
如果需要定期發(fā)送報(bào)告,這個(gè) Java 腳本與 SMTP 服務(wù)器集成,實(shí)現(xiàn)電子郵件的自動(dòng)發(fā)送,節(jié)省時(shí)間。
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.網(wǎng)站狀態(tài)檢查器
若需要監(jiān)控網(wǎng)站的正常運(yùn)行時(shí)間,這個(gè)腳本可以實(shí)現(xiàn)定期向你的網(wǎng)站發(fā)送請(qǐng)求,并在網(wǎng)站宕機(jī)時(shí)通知到你。
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,在終端獲取每日天氣預(yù)報(bào)??梢愿鶕?jù)位置定制特定更新。
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.自動(dòng)密碼生成器
使用此腳本生成安全、隨機(jī)的密碼。你可以指定長(zhǎng)度、復(fù)雜性,甚至批量輸出密碼列表。
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 文檔時(shí),這個(gè) Java 腳本將多個(gè) PDF 文件合并為一個(gè),使文件管理更簡(jiǎn)單。
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.屏幕截圖捕獲器
程序化地捕獲屏幕截圖。使用它來(lái)創(chuàng)建屏幕快照或自動(dòng)化需要視覺(jué)文檔的工作流程。
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.");
        }
    }
}














 
 
 



















 
 
 
 