简体   繁体   中英

ClassNotFoundException in main class

I am trying to code a Java app that pulls data from Yahoo Finance API. I am using Yahoo's example as reference. It compiles correctly when I -cp commons-httpclient-3.1.jar. However, when I run it, I get an error saying that the main class was not found. From my research, I assume that this is a result of a class that was there during compile is missing during run time. Any suggestions?

Here is the [full error]

在此处输入图片说明

This is the jar file I am -cp'ing: http://mvnrepository.com/artifact/commons-httpclient/commons-httpclient/3.1

Here is the snippet of code:

import java.io.*;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;

public class YahooWebServiceGet {   

public static void main(String[] args) throws Exception {
    String request = "http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=umbrella&results=10";

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(request);

    // Send GET request
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
    }
    InputStream rstream = null;

    // Get the response body
    rstream = method.getResponseBodyAsStream();

    // Process the response from Yahoo! Web Services
    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();
}

}

I can see from your screen capture that your classpath only refers to the commons library, and not your class as well. If you class is in the current directory, add ;. to your classpath (or change the dot to the directory the class is in). Also you don't want to specify .class on the class you want to run. It will add that.

java -cp ~/Downloads/commons-httpclient-3.1.jar;. YahooWebServiceGet

With java you dont specify the class file directly. It could be in a jar or anywhere on the classpath. So you need to provide the full classpath, and then the java class with any package information, and without the .class extension. eg. my.package.MyClass

What's your cammond ? you should add -cp . when run the class file like :

java -cp .;xxx.jar YahooWebServiceGet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM