At times, I’ve found myself wanting to have a specific JDK available without installing another version of Java. Past reasons include wanting to test multiple Java versions on the same system or needing to use a Java tool (ex. JConsole) without installing additional software.
With a small PowerShell script and 7-Zip installed*, you can easily create a stand-alone JDK from a JDK installer.
param
(
[string] $jdkPath = $(throw "-jdkPath is required."),
[string] $outputPath = $(throw "-outputPath is required.")
)
if (Test-Path "$env:ProgramFiles\7-Zip\7z.exe")
{
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
}
else
{
throw "$env:ProgramFiles\7-Zip\7z.exe needed"
}
function Extract-File($file, $destination)
{
sz x "$file" "-o$destination" -y
}
function Unpack($directory)
{
$files = Get-ChildItem $directory -recurse -filter "*.pack"
foreach ($file in $files)
{
$oldFile = $file.fullname
$newFile = $oldFile.substring(0, $oldFile.length - 5) + ".jar"
Write-Host "Unpacking $newFile"
Start-Process "$directory\bin\unpack200" "$oldFile $newFile" -NoNewWindow -Wait
}
}
function Print-Version($directory)
{
Start-Process "$directory\bin\java.exe" "-version" -NoNewWindow -Wait
}
$toolsZip = Join-Path -path $outputPath -childPath 'tools.zip'
Extract-File -file $jdkPath -destination $outputPath
Extract-File -file $toolsZip -destination $outputPath
Unpack -directory $outputPath
Remove-Item $toolsZip
Print-Version $outputPath
This script has been tested with Java 1.7 and 1.8 JDK installers.
- – The implementation assumes that 7-zip is available (to enable extraction of the Java binaries from the JDK installer).