运行java程序时无法运行简单的类

时间:2017-09-21 11:47:25

标签: java

我创建了一个目录c:\ivankatrump,其中包含Trump.java

文件
package com.ivankatrump.jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class Trump {
  public static void main(String[] args) {

    String jdbcUrl = "jdbc:postgresql://localhost:5432/postgres";
    String username = "postgres";
    String password = "123456";

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {

      // Step 2 - Open connection
      conn = DriverManager.getConnection(jdbcUrl, username, password);

      // Step 3 - Execute statement
      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT version()");

      // Step 4 - Get result
      if (rs.next()) {
        System.out.println(rs.getString(1));
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }  finally {
      try {

        // Step 5 Close connection
        if (stmt != null) {
          stmt.close();
        }
        if (rs != null) {
          rs.close();
        }
        if (conn != null) {
          conn.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

  }
}

我可以使用javac Trump.java进行编译,但是当我尝试使用java Trump运行时,

我收到错误

  

错误:无法找到或加载主类Trump.class

这是echo %CLASSPATH%的样子

c:\donaldtrump>echo %CLASSPATH%

c:\classpath\antlr-2.7.7.jar;c:\classpath\classmate-1.3.0.jar;c:\classpath\dom4j-1.6.1.jar;c:\classpath\hibernate-commons-annotations-5.0.1.Final.jar;c:\classpath\hibernate-core-5.2.11.Final.jar;c:\classpath\hibernate-jpa-2.1-api-1.0.0.Final.jar;c:\classpath\jandex-2.0.3.Final.jar;c:\classpath\javassist-3.20.0-GA.jar;c:\classpath\jboss-logging-3.3.0.Final.jar;c:\classpath\jboss-transaction-api_1.2_spec-1.0.1.Final.jar;c:\classpath\postgresql-42.1.4.jar

为什么系统无法找到Trump.class?

修改

以这种方式编译c:\ivankatrump>javac -d . Trump.java编译,但也不运行。

1 个答案:

答案 0 :(得分:2)

简短说明: 尝试创建文件夹comdonaldtrumpjdbc。把java类放在那里。然后,

javac com/donaldtrump/jdbc/Trump.java
java com/donaldtrump/jdbc/Trump

更好的解释:

What does "Could not find or load main class" mean?