Fully understand the "package" mechanism in Java

Source: Internet
Author: User

Body

The "package" mechanism is unique in Java and the most basic knowledge in Java. Some beginners of Java usually copy some programs from the textbooks to run like other languages, but often encounter inexplicable error prompts. In fact, the principle of "packets" is not clear enough. This article will elaborate on this issue in depth.

I. Why is the concept of "package" required in Java?

In a word, the main reason for the introduction of "packages" in Java is the demand for cross-platform features of Java. Because all resources in Java are also organized as files, which mainly contains a large number of class files that need to be organized and managed. The directory tree structure is also used in Java. Although the management of files on various common operating system platforms is organized in the form of a directory tree, they separate directories in different expressions. to distinguish them from various platforms, Java uses ". to separate directories.

2. Connection Between the Java package structure and the Platform

Resources in Java may vary greatly when they exist on different platforms. Therefore, the cross-platform Java Package Structure and platform must be linked together in one way. In fact, they are linked together through the classpath settings we are very familiar. For example:

My classpath settings in Windows2000 are as follows:

classpath = d:/jdk1.4.2/lib/dt.jar; d:/cjm 

Class cohesion can be used to express:

It can be seen that the classes in Java are "suspended". In this way, they can be placed on any platform at will, but a class should be correctly located under the platform, you must use classpath to set the first part of the class directory (that is, the part different from the platform ). In Java, a class tree is often compressed into one. JAR file, Rt. jar, which does not affect the search for classes. You can specify it when specifying environment variables. the directory where the JAR file is located. jar full search path, that is, the classpath in the above example can also be described:

classpath = d:/jdk1.4.2/lib; d:/cjm

When the classpath environment variables under the platform are correctly set, the cross-platform Java features are reflected. That is, when you write a program to describe a class, you do not need to specify its complete path, but only specify the class path in Java, that is, you can find the path on the right of the vertical line in Figure 1. In this way, when the program you write gets to any platform, you only need to write the corresponding classpath environment variables according to the directory where the class files are stored, you do not need to modify the program because the class storage environment changes.

Note: in Java, the search for a class is to connect each item in classpath one by one. When a connection can correctly find the relevant class, it will not look back.

3. correct use of the "package"

There are a lot of small details to be aware of when using the package. The common problems are listed as follows:

1. You can set the classless path in two ways:

I) set in the system environment variables and the setting method changes based on the platform;

Ii) It is set as a command parameter.

For example, javac-classpath D:/jdk1.4.2/lib D:/CJM/edu/test/testfile. java-classpath .; d:/jdk1.4.2/LIB; D:/CJM Edu. test. testfile

Note: I) javac differs greatly from Java commands. javac is a platform command that operates on a specific platform file and specifies the path of the compiled file. Java is a virtual machine command, which performs class operations, that is, class description must be in the form of a point description, and cannot add extensions. Pay attention to the Case sensitivity of the class name.

Ii) There is a strange problem: the classpath after the javac command contains the current directory by default (in line with Windows's habits), but the classpath after the Java command does not contain the current directory, therefore, you must not forget to add the description of the current directory to its classpath, that is, add ". ".

2. in Java, the class path description is separated by ".", and the concept of the current directory also exists. To run testfile in Figure 1, it must be specified as Edu. Test. testfile. However, if you want to call teststring in the same directory as testfile, you do not need to specify the directory prefix.

3. All classes used in the Java program should clearly specify the search path for this class. There are two methods to specify:

I) use the import keyword at the beginning of the program. If the fileinputstream class is used in testfile, add import java. Io. filereader or import java. Io. * to the program header .*;

Ii) write the complete path directly in the filefilereader class in the program, for example, java. Io. filefilereader fin = new java. Io. filereader ("FILENAME ");

Note: The java. lang Package is always imported by default.

4. the directory structure of the class must be consistent with the first "package Declaration" in the class. For example, the first sentence of the. Java file corresponding to testfile. Class must include package edu. test;

There are two methods to ensure that the class storage path is consistent with the "package path" specified in the class:

I) The Directory stored in the. Java file is determined in advance. For example, testfile. Java is directly stored in the edu/test directory, and then compiled using the following statement:

javac -classpath d:/jdk1.4.2/lib d:/cjm/edu/test/TestFile.java 

After the compilation is complete, the generated testfile. Class file will appear in the description path of the Java file in the compilation command. It appears in D:/test/edu/test.

Ii) Compile the program using the-D parameter. For example, compile with the following statement:

javac -d d:/cjm d:/temp/TestFile.java

The Directory D:/CJM specified after-D is automatically created according to the directory structure specified in packagek. the class file is placed under the new directory, that is, the/edu/test directory is created under D:/CJM, and then the testfile is generated. class is stored in the Directory D:/CJM/edu/test.

5. To facilitate project release, you can compress your class tree into A. jar file. For example, if you type all the class files under Edu in Figure 1 into a. jar file, you can first go to the D:/CJM directory and use the following command:

   jar -cvf test.jar edu/

A test. jar file is generated under D:/test. The. jar file contains the complete directory structure and file under edu. When using this. jar file, you only need to specify the path to store the. jar file in classpath.

6. You must pay attention to the use of other resources, standard files, text and other resource files. The search for resource files should not start from the directory where the class files are located, instead, it should start from the starting point of the class path specified by the package (Figure 1 starts from the directory where Edu is located ). The example file word.txt found in 1 is under resource, and the class file testfile. Class is under edu/test. use word.txt in resourcein testfile.class. follow these steps:

Fin = new filereader ("resource/word.txt"); it should not be: fin = new filereader (".../../resource/word.txt ");

Iv. Examples

This example is used to count the number of words in a text file. The numbers in the comment correspond to the numbers in the previous section:

//TestFile.java package edu.test;//--------------------------------------- 4 import java.io.FileReader;//------------------------------ 3 import java.io.LineNumberReader; class TestFile{ public static void main(String []argv){ TestString ts = new TestString();//---------------- 2 FileReader fin; LineNumberReader line = null; int wordNum = 0; try{ fin= new FileReader("resource/word.txt");//---- 6 line = new LineNumberReader(fin); }catch(Exception e){ e.printStackTrace(); System.exit(0); } while(true){ try{ String temp = line.readLine(); wordNum += ts.CountWord(temp); }catch(Exception e){ break; } } try{ line.close(); }catch(Exception e){}; System.out.println("Word count is:" + wordNum); } }

//TestString.java package edu.test; import java.util.*; class TestString { int CountWord(String str){ StringTokenizer token = new StringTokenizer(str); return token.countTokens(); } }

The two. java files are stored in the D:/TEMP directory. The current directory is D:/temp and compiled using the following command:

d:/temp>javac -classpath d:/jdk1.4.2/lib -d d:/test *.java

Run the following command:

//--------------------------------- 1 d:/temp> java -classpath .;d:/jdk1.4.2/lib; d:/test/com edu.test.TestFile 

To pack the package, first go to D:/test and run the following command:

//--------------------------------- 5 jar -cvf test.jar edu/ 

In this case, you can generate a test. jar file that can be used on any platform.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.