Search code examples
javapackagejavac

Package not found error when compiling with javac -d flag?


I'm trying to compile a Servlet Class called as BeerSelect.java . It imports a Model Class BeerExpert.java from a package , Problem is while compiling I get a package not found error .

My directory structure is as below

diectory structure

I first Compiled my BeerExpert.java as follows

went to beerV1 and

javac -d classes /src/com/example/model/BeerExpert.java

and the .class file automatically got created in the correct path as shown above

Now again from beerV1 directory I try to compile the BeerSelect.java as ...

javac -classpath ~/tomcat/lib/servlet-api.jar -d classes/ src/com/example/web/BeerSelect.java 

it throws this error

src/com/example/web/BeerSelect.java:2: error: package com.example.model does not exist
import com.example.model.*;
^

The two java files

BeerSelect.java

package com.example.web;
import com.example.model.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import javax.servlet.http.*;

public class BeerSelect extends HttpServlet
{
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
    {

    response.setContentType("text/html");

    PrintWriter out=response.getWriter();

    String beerColor=request.getParameter("color");

    BeerExpert expert=new BeerExpert();
    ArrayList brands=expert.getBrands(beerColor);


    for(String brand:brands)
    {
        out.println("Try  "+brand+"<br>");
    }

        }//post ends

    }//class ends

BeerExpert.java

package com.example.model;

import java.util.*;

public class BeerExpert {

    public ArrayList<String> getBrands(String color)
    {
        ArrayList<String> brands=new ArrayList<>();

        if(color.equals("Dark"))
        {
            brands.add("Dark fantasy");
            brands.add("Dark Warrior");
        }
        else//light
        {
            brands.add("Light as a feather");
            brands.add("light as a macbook");
        }

        return brands;
    }
}

Why can't it see the package? Please help :(


Solution

  • Oops it was a silly mistake

    javac must know where to look for the package

    so adding the location to classpath did the trick

    I used

    javac -classpath ~/tomcat/lib/servlet-api.jar:**classes** -d classes/ src/com/example/web/BeerSelect.java 
    

    Works now :)