Running Java program from Linux command line that

2019-07-26 01:56发布

问题:

I am following this tutorial to make a program that interacts with the database. I am stuck at the last step where I run it. The given example is C:\test>java -cp c:\test\postgresql-8.3-603.jdbc4.jar;c:\test JDBCExample

I have both the .class file and the .jar for the JDBC in my home directory. I tried

java -cp /home/JohnF/postgresql-9.2-1000.jdbc4.jar;/home/JohnF/QueryDB.class and I get "cannot exectue binary file"
I tried java -cp /home/JohnF/postgresql-9.2-1000.jdbc4.jar;/home/JohnF/QueryDB and I get "no such file or directory"
I tried java -cp /home/JohnF/postgresql-9.2-1000.jdbc4.jar;/home/JohnF QueryDB and I get "JohnF is a directory"

I used chmod to set the file permissions to 777. How do I get this to run?

回答1:

You are using semicolon as classpath separator - this will not work on Linux. Try replacing ";" with ":" in classpath and it should work.

Edit: explanation of what is happening here. In Linux, ";" is command separator. Your line of

java -cp /home/JohnF/postgresql-9.2-1000.jdbc4.jar;/home/JohnF QueryDB

is really expanded into 2 executed one by one:

java -cp /home/JohnF/postgresql-9.2-1000.jdbc4.jar
/home/JohnF QueryDB

First one does nothing and successfully quits. Second tries to invoke /home/JohnF as executable, and this is really not an executable, but a directory!



回答2:

FIX: Use : instead of ;

WHY? The file-separator in *nix environment is ':' and not ';'