简体   繁体   English

如何导入包装中的jar文件?

[英]How to import a jar file which is in a package?

I have a jar file named stdlib-package , the .class files in this jar file are all in a edu.princeton.cs.introcs package 我有一个名为stdlib-package的jar文件,此jar文件中的.class文件全部位于edu.princeton.cs.introcs包中

For example, I want to use one class named StdDraw from that jar file in my own codes 例如,我想在自己的代码中使用该jar文件中的一个名为StdDraw的

Say E:\\code is my current working directory. E:\\ code是我当前的工作目录。 like other conditions, I create a subdirectory bin\\edu\\princeton\\cs\\introcs to put stdlib-package in 像其他情况一样,我创建了一个子目录bin \\ edu \\ princeton \\ cs \\ introcsstdlib-package放入

Here is my codes: 这是我的代码:

package com.david.test;
import edu.princeton.cs.introcs.stdlib-package.*; // any problems here ?

public class DrawTest
{
    public static void main(String[] args)
    {
        StdDraw.line(0.5, 0.5, 1, 0.5);
    }
}  

Then I put DrawTest.java in the src\\com\\david\\test 然后我将DrawTest.java放在src \\ com \\ david \\ test中

To compile the DrawTest.java , I type the commands in command line: 要编译DrawTest.java ,我在命令行中输入命令:

javac -d bin -cp bin\edu\princeton\cs\introcs\stdlib-package.jar src\com\david\test\DrawTest.java  

But it failed : package edu.princeton.cs.introcs.stdlib_package doesn't exist... 但是失败了:包edu.princeton.cs.introcs.stdlib_package不存在...

I searched for a lot of time, but haven't found the answer 我搜索了很多时间,但没有找到答案
Thanks for your help 谢谢你的帮助

EDIT=== 编辑===
@EJP's comment solves my question too. @EJP的评论也解决了我的问题。

This should be all you need in code: 这应该是代码中所需要的:

import edu.princeton.cs.introcs.*

Then you only need to make sure the jar is on your class path; 然后,您只需要确保jar在类路径中即可; it doesn't matter what the name of the jar is, or where it is. 罐子的名称是什么,或在哪里都无所谓。 If it is on your classpath, Java will load it, and use the location of the files within it. 如果它在您的类路径中,则Java会加载它,并使用其中文件的位置。

Move the jar into a lib directory in your current directory, and do something like 将jar移到当前目录的lib目录中,然后执行类似的操作

javac -cp lib\stdlib-package.jar src\com\david\test\DrawTest.javac

Your import is wrong. 您的输入错误。 There's no such package in that .jar file. 该.jar文件中没有此类软件包。

import edu.princeton.cs.introcs.*; 

In general, however, that's a bad practice and you should really only import what you need: 但是,总的来说,这是一个不好的做法,您实际上应该只导入所需的内容:

import edu.princeton.cs.introcs.StdDraw;

I understand that there is no package with 'stdlib-package' name. 我知道没有名为“ stdlib-package”的软件包。

If the fully qualified name of the class you are using is edu.princeton.cs.introcs.StdDraw, you can just import 'edu.princeton.cs.introcs.StdDraw' 如果您正在使用的类的标准名称是edu.princeton.cs.introcs.StdDraw,则只需导入“ edu.princeton.cs.introcs.StdDraw”

     import edu.princeton.cs.introcs.StdDraw

If you want to load all the classes in that package 如果要加载该包中的所有类

     import edu.princeton.cs.introcs.*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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