首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 讀取 Excel 檔案並依路徑複製編譯類別檔至指定目錄完整範例

     編輯:Java 程式設計入門

概述

本範例示範如何使用 Apache POI 庫讀取 .xls 格式的 Excel 檔案,從指定工作表中提取檔案路徑清單,再根據這些路徑將編譯後的 .class 檔案(含內部類別)從來源目錄複製到部署目錄。程式碼採用命令列參數傳入 Excel 目錄、來源類別目錄、目標部署目錄以及 Web 內容根目錄(預設 WebContent),適合自動化部署流程。

核心類別架構

DeployByExcel 主類別

  • getDatasInSheet(int sheetNumber, File dir):掃描目錄下所有 .xls 檔,讀取指定工作表,從第 5 行開始逐行取得第 2 欄(索引 1)的字串值,組成檔案路徑清單回傳。
  • copy(String sourcePath, String destPath, List<String> fileList, String webContent):遍歷路徑清單,將 .java 替換為 .class,並根據路徑前綴(src/ 或 Web 內容目錄)轉換為 WEB-INF/classes/ 或相對路徑,呼叫 copyFile 執行實際複製,同時處理內部類別檔(如 ClassName$1.class)。
  • copyFile(String str, String sourcePath, String destPath):建立目標目錄,以 1KB 緩衝區逐塊複製檔案,回傳布林值表示成功與否。
  • getCellString(HSSFCell cell):根據儲存格型別(字串、數值、公式、布林、空白、錯誤)提取對應值。

關鍵程式碼片段

// 讀取 Excel 並取得路徑清單
public List<String> getDatasInSheet(int sheetNumber, File dir) throws FileNotFoundException, IOException {
    List<String> result = new ArrayList<>();
    File[] files = dir.listFiles();
    for (File f : files) {
        if (!f.getName().toLowerCase().endsWith(".xls")) continue;
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(f));
        HSSFSheet sheet = workbook.getSheetAt(sheetNumber);
        int rowCount = sheet.getLastRowNum();
        for (int rowIndex = 4; rowIndex <= rowCount; rowIndex++) {
            HSSFRow row = sheet.getRow(rowIndex);
            if (row != null) {
                HSSFCell cell = row.getCell(1);
                String str = (String) getCellString(cell);
                if (str != null && str.length() > 1) result.add(str);
            }
        }
    }
    return result;
}

// 複製單一檔案(含建立目錄)
private boolean copyFile(String str, String sourcePath, String destPath) throws IOException {
    File sourceFile = new File(sourcePath + str);
    if (!sourceFile.exists()) return false;
    File destFile = new File(destPath + str);
    File destDir = new File(destFile.getParent());
    if (!destDir.exists()) destDir.mkdirs();
    try (InputStream in = new FileInputStream(sourceFile);
         FileOutputStream out = new FileOutputStream(destFile)) {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len);
        return true;
    }
}

執行方式

java DeployByExcel <Excel目錄> <來源類別目錄> <部署目標目錄> [WebContent目錄名]

範例:

java DeployByExcel /tmp/excel /project/build/classes /deploy/target WebContent

注意事項

  • 僅支援 .xls (HSSF),若需 .xlsx 請改用 XSSFWorkbook。
  • Excel 檔案中路徑應為相對專案根目錄的路徑,程式會自動轉換 src/ 為 WEB-INF/classes/。
  • 內部類別檔($1.class、$2.class…)會自動嘗試複製,直到找不到為止。
  • 使用 Log4j 記錄資訊與錯誤,部署前請確認類別路徑包含 log4j.properties。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved