3

I am having trouble running a Java program with Windows Powershell 2.0. Any help on this would be greatly appreciated. I want the string "Hello World!" to print to the main Powershell console window. Instead, its getting printed to a separate process window that opens then suddenly closes. I don't know exactly how to tell the powershell to redirect the stdout of the spawned java process to the current powershell console. Basically, i want behavior just like what I get when running java under a DOS shell.

My test class is:

class HelloWorldApp { 
    public static void main(String[] args) { 
        System.out.println("Hello World!"); //Display the string. 
    } 
} 

My PowerShell 2.0 code is this:

set-item -path Env:CLASSPATH -value C:\Test 
"CLASSPATH = $Env:CLASSPATH" 
[Diagnostics.Process]::Start('java.exe','-classpath $Env:CLASSPATH C:\
Test\HelloWorldApp') 

Alternatively, I tried to run it like so, as I would with a regular DOS shell, with the hope that the output shows in the same console :

java.exe -classpath $Env:CLASSPATH C:\Test\HelloWorldApp 

It causes an error. I get this error:

PS >C:\Test\Test.ps1 
CLASSPATH = C:\Test 
java.exe : java.lang.NoClassDefFoundError: C:\Test\HelloWorldApp 
At C:\Test\Site.ps1:3 char:5 
+ java <<<<  -classpath $Env:CLASSPATH C:\Test\HelloWorldApp 
+ CategoryInfo : NotSpecified: (java.lang.NoCla...e\HelloWorldApp: 
                               String) [], RemoteException 
+ FullyQualifiedErrorId : NativeCommandError 
Exception in thread "main" 

As far as I can tell, my args are correct because here is what the PCEX ( http://pscx.codeplex.com ) echoargs cmdlet tells me:

PS >echoargs java.exe -classpath $Env:CLASSPATH C:\Test\HelloWorldApp 
Arg 0 is <java.exe> 
Arg 1 is <-classpath> 
Arg 2 is <C:\Test> 
Arg 3 is <C:\Test\HelloWorldApp> 

Im convinced there is a way to get this to work because this code works:

## Test.ps1
cd C:\PSJustice
java.exe -classpath . HelloWorldApp

Also, this works:

cd C:\
java.exe -classpath C:\Test HelloWorldApp
1
  • You're getting the NoClassDefFoundError because java.exe expects to be invoked from the directory that the class is in (or the root of the package structure). Don't know about the PowerShell part though. Commented Jul 1, 2009 at 22:10

1 Answer 1

5

I finally figured it out. It was the smallest typo :

cd c:\
set-item -path Env:CLASSPATH -value C:\Test 
"CLASSPATH = $Env:CLASSPATH" 
java.exe -classpath $Env:CLASSPATH HelloWorldApp

When specifying the Class name it cannot include the absolute path prefixing the class name. Oops.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.