执行 Copy/Merge 时批量删除文件

Batch Deleting Files While Performing a Copy/Merge

我有 2 个文件,"launcher.jar" 和 "camStudio.jar" 需要合并。我决定尝试使用代码批处理来做到这一点:

copy /b launcher.jar + camStudio.jar file.jar

然而,结果"file.jar"只包含"camStudio.jar"的内容。如何防止"launcher.jar"中的文件被删除?

合并两个 .jar 文件的内容比仅从命令行调用 copy 稍微复杂一些。 .jar 文件不是普通目录,而是一种压缩文件,因此您需要特殊的实用程序来操作它们。幸运的是,这些工具与标准 JKD 一起提供。

JDK 附带实用程序 jar,不出所料,它用于操作 .jar 文件。它的用法描述如下:

Usage: jar {ctxui}[vfmn0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
    -c  create new archive
    -t  list table of contents for archive
    -x  extract named (or all) files from archive
    -u  update existing archive
    -v  generate verbose output on standard output
    -f  specify archive file name
    -m  include manifest information from specified manifest file
    -n  perform Pack200 normalization after creating a new archive
    -e  specify application entry point for stand-alone application
        bundled into an executable jar file
    -0  store only; use no ZIP compression
    -M  do not create a manifest file for the entries
    -i  generate index information for the specified jar files
    -C  change to the specified directory and include the following file
If any file is a directory then it is processed recursively.
The manifest file name, the archive file name and the entry point name are
specified in the same order as the 'm', 'f' and 'e' flags.

Example 1: to archive two class files into an archive called classes.jar:
       jar cvf classes.jar Foo.class Bar.class
Example 2: use an existing manifest file 'mymanifest' and archive all the
           files in the foo/ directory into 'classes.jar':
       jar cvfm classes.jar mymanifest -C foo/ .

合并两个.jar文件的相关命令是xc。即使这样,组合 .jar 文件也需要一两行以上的时间,所以我将这个 .bat 文件放在一起以使其自动化。

:: Pass one or more .jar files as command line arguments
:: Combine_Jar [file1] [file2 ...]
:: Combine_Jar Test.jar
:: Combine_Jar Test.jar Test2.jar Test3.jar
@echo off & setlocal enabledelayedexpansion

set "jarDir=%cd%"
set "newJar="
set "folders="
pushd %temp%
for %%a in (%*) do (
    call :extract %%a
    set "newJar=!newJar!_%%~na_"
)



set "tempDirs=!newJar:_=^"!"
set "tempDirs=%tempDirs:^"^"=^" ^"%"

set "newJar=!newJar:~1,-1!.jar"
set "newJar=!newJar:__=_!"
if exist "!newJar!" del /Q "!newJar!"

jar cf "!newJar!" %tempDirs%

for %%a in (%*) do call rd /s /q  "%%~na"

move /Y "!newJar!" "%jarDir%" > nul
popd
exit /B

:extract
set "tempDir=%~n1"

if exist "%tempDir%" (
    rd /s /q "%tempDir%"
)
md "%tempDir%"

pushd "%tempDir%"
jar xf "%jarDir%\%~1"
popd
exit /B

它将所有 jar 文件作为参数传递到单个 jar 文件中。