自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

十個Java自動化腳本,開發(fā)效率倍增

開發(fā) 前端
Java 不僅是非常強大的應用開發(fā)語言,更是自動化的利器。本文分享10個能讓你事半功倍的 Java 腳本,助你一臂之力,提高工作效率。

Java 不僅是非常強大的應用開發(fā)語言,更是自動化的利器。本文分享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.每日備份系統(tǒng)

安排一個 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.數(shù)據(jù)庫清理

使用此腳本定期清除舊記錄或不必要的數(shù)據(jù)。設置按計劃刪除過時的條目,以保持數(shù)據(jù)庫優(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.郵件自動化

如果需要定期發(fā)送報告,這個 Java 腳本與 SMTP 服務器集成,實現(xiàn)電子郵件的自動發(fā)送,節(jié)省時間。

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)站的正常運行時間,這個腳本可以實現(xiàn)定期向你的網(wǎng)站發(fā)送請求,并在網(wǎng)站宕機時通知到你。

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,在終端獲取每日天氣預報??梢愿鶕?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.自動密碼生成器

使用此腳本生成安全、隨機的密碼。你可以指定長度、復雜性,甚至批量輸出密碼列表。

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.屏幕截圖捕獲器

程序化地捕獲屏幕截圖。使用它來創(chuàng)建屏幕快照或自動化需要視覺文檔的工作流程。

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.");
        }
    }
}
責任編輯:武曉燕 來源: Java學研大本營
相關推薦

2024-10-28 19:36:05

2024-06-21 10:46:44

2024-08-14 14:42:00

2024-07-01 18:07:30

Python腳本自動化

2024-12-10 00:01:00

自動化腳本優(yōu)化

2025-03-17 09:32:19

PythonExcel腳本

2022-05-07 14:08:42

Python自動化腳本

2022-10-09 14:50:44

Python腳本

2022-07-27 08:01:28

自動化DevOps

2022-07-05 14:00:49

編排工具自動化

2024-08-19 10:21:37

接口Python魔法方法

2024-08-16 21:14:36

2022-09-20 15:43:58

Python工具包編程

2024-05-13 16:29:56

Python自動化

2024-05-28 14:36:00

Python開發(fā)

2023-09-21 22:56:32

插件開發(fā)

2023-10-27 18:11:42

插件Postman代碼

2023-02-15 08:34:12

測試移動開發(fā)

2023-09-07 10:21:03

VS Code 技巧提高開發(fā)效率

2024-03-17 20:01:51

點贊
收藏

51CTO技術棧公眾號