Java FAQ Collection--from Sun China official station __java

Source: Internet
Author: User
Tags driver manager netscape web server thread class
This is an article I saw in other forums, I think it's not bad. Let's share them. I hope to help you a little. A za a za fighting!


Ask:
How do I set the environment variables for Java 2 (JDK1.2)?

For:
After Java 2 is installed, you need to set up path and java_home environment variables. Unlike JDK1.1, when you set the JAVA_HOME environment variable, the JVM automatically searches the System class library and the user's current path.

The settings for the Java 2 environment variable are as shown in the following example:

Solaris Platform: Installation path for setenv java_home Java2

Setenv path/bin:/p/2002-11-14/6302.html

Windows platform: Installation path for set JAVA_HOME=JAVA2

Set path=;%path%

Q: Which Java integrated development tools support Java 2?

For:
The current popular Java integrated development environment, such as Inprise's Jbuilder,symantec visual Cafe, Sybase's Powerj, supports Java 2.

Ask:
If an error occurs when running Java applets in Netscape or IE browsers, how do you determine the error range?

For:
When Java applets are run in a browser, the default JVM of the browser itself is used, and the degree to which the JDK is supported by different browsers varies. Therefore, there is an error running the Java applet in Netscape or IE browsers, and it is recommended that you use the tools provided by JDK Appletviewer or Sun's HotJava browser to test the applet to determine that the error occurred in browser-related.

If the applet is working properly in appletviewer or HotJava, the error arises because the browser is not fully compliant with the JDK. At this point, the workaround could be to use the HotJava browser or install Sun Company's Java Plugin.

If an applet has an error running in HotJava browser or appletviewer, you should check the applet according to the error prompts.

Ask:
When you use JDBC to insert data into a database or extract data from a database, why do Chinese characters sometimes appear garbled?

For:
The implementation of this problem is usually related to the implementation of each JDBC driver. Most JDBC driver currently use the local encoding format to transmit Chinese characters, such as the Chinese character "0x4175" to be transferred to "0x41" and "0x75". So we need to convert the characters returned by the JDBC driver and the characters to be sent to the JDBC driver.

When inserting data into a database with JDBC driver, Unicode must first be converted to native code; When JDBC driver queries data from a database, you need to convert native code to Unicode. The implementation of these two transformations is given below:

String Native2unicode (string s) {

if (s = = NULL | | s.length () = 0) {

return null;

}

byte[] buffer = new byte[s.length ()];

for (int i = 0; I s.length (); i++) {if (S.charat (i) >= 0x100) {

c = S.charat (i);

byte []buf = ("" +c). GetBytes ();

Buffer[j++] = (char) buf[0];

Buffer[j++] = (char) buf[1];

}

else {

Buffer[j++] = S.charat (i);

}

}

return new String (buffer, 0, J);

}

In addition to using the two methods above, some JDBC driver the above 2 methods are not required if the correct character set attributes are set on the JDBC Driver manager.

Ask:
When using a servlet to process an HTTP request and produce a returned HTML page, how do I make the Chinese characters in an HTML page appear correctly?

For:
The Javax.servlet.http.HttpResponse class is used to generate a return page. The HttpResponse defined Method Getoutputstream () can obtain an instance of Servletoutputstream. This allows the user to write the contents of the returned page to the output stream using the Servletoutputstream.write method. But Servletoutputstream uses the default encoding, and if you want to make the Chinese characters in the return page appear correctly, It is best to specify the character encoding used. Typically, you need to construct a outputstreamwriter, as follows:

public void Doget (HttpServletRequest req, httpservletresponse Res)

Throws Servletexception, IOException

{

Res.setcontenttype ("text/html");

Servletoutputstream out = Res.getoutputstream ();

OutputStreamWriter ow = new OutputStreamWriter (out, "GB2312");

Ow.write ("This is the test");

Ow.flush ();

Ow.close ();

}

Ask:
How do I set the Java webserver classpath to contain the user's class file?

For:
There are two ways to set the Java webserver classpath environment variable so that the user-written servlet can invoke the user's class file.
The user's class file is placed in the Javawebserver_dir/classes directory, and the classes directory is automatically added to the CLASSPATH environment variable when the Java WebServer is started.
Modify the Httpd.nojre file to add the path name of the user class file to the CLASSPATH environment variable.

Ask:
Why is it slow to get a remote RMI object with Naming.lookup on a Windows platform?

For:
The incorrect network settings for the machine are likely to cause the problem to occur.
RMI uses Java network classes, especially the Java.net.InetAddress class, which queries TCP/IP host names, including mappings of IP addresses to host names and mappings of host names to IP addresses. On the Windows platform, this query function is made up of local windows Socket library to implement. Therefore, latency occurs in the Windows Library, not in RMI.

If your machine is set to use DNS, the problem is usually that the DNS server does not find the host name, and the latency you find is the latency of DNS queries. Try adding all the hostname/IP addresses involved in RMI traffic to the local file winntsystem32driversetchosts or windowshosts. The format is as follows:

IP Address host Name

This setting should significantly reduce the time that the query takes.

Q: When writing Java application, how do I set the proxy information to access the external Web site?

For:
If you are accessing an external Web site in the Java application, you should first set proxy information, the sample code is as follows:


Import java.util.properties;

.....

Properties sys = system.getproperties ();

Sys.put ("Proxyset", "true");

Sys.put ("ProxyHost", "myHTTP.proxyserver.com");

Sys.put ("ProxyPort", "80");

System.setproperties (SYS);

u = new URL (website);

Connect = (httpurlconnection) u.openconnection ();

.....

Q: The Swing component JList list data has been modified, how to notify the JList change display?

For:
The JList component has a separate display mode Listmodel to represent the jlist display data.
After the jlist is created, the value of the JList data element and the number of data elements can be changed dynamically.
JList observes the data changes in its data pattern listmodel. Therefore, a listmodel proper implementation should notify the listener of the event every time the data has changed.
When a JList instance is created using the constructor jlist (object[]), an instance of Defaultlistmodel is automatically created to store the jlist display data, which can be invoked The simple method defined in Defaultlistmodel modifies jlist data dynamically, such as Removeelementat (index), addelement (Object), and so on. Defaultlistmodel while modifying the data, Will notify JList about changes to the data.

Ask:
How do I implement a modal dialog box in Java applets?

For:
The key to implementing a modal dialog box in a Java applet is to specify a correct parent window for the dialog box when you create a dialog box. Because applets are subclasses of the Panel class and cannot be the parent window of the dialog box, you first get the window that the applet is in as a pattern The parent window of the dialog box. The sample code is as follows:
.....

Dialog d = new Dialog (Getparentwindow (comp), title);

Comp as any one of the components on the applet

....
public void Getparentwindow (Component componapplet,string title) {
Container C = componapplet.getparent ();
while (c!= null) {
if (c instanceof Frame)
Return (Frame) C;
c = c.getparent ();
}
return null;
}

Q: How do i display another HTML page in a Java applet?

For:
The Appletcontext, appletcontext.showdocument (URL) associated with the applet can be obtained by the Java.applet.Applet.getAppletContext () method. method to display another Web page in the browser that the applet is in.

Ask:
Can a signed applet, implemented with JDK, run in Netscape or IE?

For:
A signed applet, implemented with JDK, cannot be run in Netscape or IE, but can be run in the HotJava browser.

Different browsers offer different signature applet mechanisms, such as Netscape, which provides the Zigbert tool and the Capability API, while IE requires the use of a CAB file. However, neither the signature applet produced by Netscape Tools nor the signed applet produced with IE can be run in other browsers.

If you want the JDK-generated signature applet to run in Netscape or IE, the solution is to install Java Plugin in Netscape or IE, the signed applets implemented with JDK can be run in both browsers.

Ask:
JNI technology allows you to invoke the C program library from Java applications, but how do you make the C program library call another C library?

For:
If a Java-invoked C-Library C1 still needs to invoke another C-Library C2, you should join the library C2 when compiling C1, as follows (Solaris platform):
Write the Java file that calls the C library and compile it.
Javac java filename

Generate C Program header file
Javah-jni java filename (without suffix. java)

Write the C program c1.c that is invoked by Java, and the c2.c that is called by C1, and compile.
Cc-g-iinclude path name C2.c-o libc2.so
Cc-g-iinclude path name-LC2 c1.c-o libc1.so

Setting environment variables
setenv Ld_library_path libc1.so,libc2.so Path
:

Running Java applications

Ask:
In the Java language, how do I list all the drive names in the PC file system?

For:
In the Java 2 version, the file class in the Java.io package adds a new method Listroots () to implement this functionality.

Ask:
Why is runtime.exec ("LS") without any output?

For:
Calling the Runtime.exec method produces a local process and returns an instance of a process subclass that can be used to control the process or obtain information about the process. Because the child process created by calling the Runtime.exec method does not have its own terminal or console, the standard IO (such as Stdin,stdou,stderr) for the subprocess passes through Process.getoutputstream (). Process.getinputstream (), the Process.geterrorstream () method is redirected to its parent process. Users need to use these stream to enter data into a subprocess or to get the output of a child process. So the routines for proper execution of runtime.exec ("LS") are as follows:

Try

{

Process = Runtime.getruntime (). exec (command);

InputStreamReader Ir=newinputstreamreader (Process.getinputstream ());

LineNumberReader input = new LineNumberReader (IR);

String Line;

while (line = Input.readline ())!= null)

System.out.println (line);

}

catch (Java.io.IOException e) {

System.err.println ("IOException" + e.getmessage ());

}

Ask:
How do I generate a signed applet to enable the applet to access local resources?

For:
In jdk1.1, you can use the Javakey command to generate the public key, private key, certificate, and signature jar files, please refer to the details: Http://java.sun.com/security/usingJavakey.html and Java 2 The signature mechanism has been improved to allow users more flexibility to set security permissions. Java 2 provides three tools: Keytool,policytool and Jarsigner to implement a signed applet. For example, Joe wrote a signature Applet:SignedApplet.java, The process of producing a simple signed applet is as follows:

Generate key, key alias is Joe, password is sign12, stored in KeyStore joestore

Keytool-genkey-alias Joe-keypass Sign12-keystore Joestore

Package Signedapplet.class and related files into a jar file

Jar CVF Signedappletdemo.jar

Generate a signed applet (JAR file) with a self-signed certificate generated by Keytool

Jarsigner-keystore Joestore-signedjar Joe.jar Signedappletdemo.jar Joe

To export a self-signed certificate from KeyStore to a file

Keytool-export-keystore Joestore-alias Joe-file Joe.cer

For the recipient of the signed applet, Susan, you need to perform the following steps safely

Signed applet written by Joe:

Get Joe's certificate and read it into the KeyStore Susanstore

Keytool-import-alias joe-file Joe.cer-keystore Susanstore

Run Policytool generate policy files that meet Susan's requirements

Policytool

Run it with Appletviewer, or install Java plugin in the browser to run it.

For the deployment of a signed applet in the Java plugin, refer to the following Web page:

http://java.sun.com/security/signExample12/

Note: For simplicity, the above example uses the self-signed certificate produced by Keytool. In fact, users can also

Use Keytool-certreq to apply for an electronic certificate to the commercial CA center.

Ask:
If you write object more than once in a file by ObjectOutputStream, why do you have streamcorruptedexception when you read the object with ObjectInputStream?

For:
When using the default Serializetion implementation, A objectoutputstream structure and a objectinputstream construct must correspond to one by one. The constructor of the ObjectOutputStream writes an identity header to the output stream. And ObjectInputStream will read the header first. So, when you write an object to a file in an append way, The file will contain multiple identity headers. So when you use ObjectInputStream to deserialize this objectoutputstream, will produce streamcorruptedexception. One workaround is to construct a objectoutputstream subclass and overwrite the Writestreamheader () method. Writestreamheader after being covered () method should determine whether to write the object to the file for the first time, or to invoke Super.writestreamheader (), or to call the Objectoutputstream.reset () method if no, that is, when the object is written in an append way.

Ask:
The serialized (serialization) class of an object is stream oriented, how should the object be written to a random access file?

For:
Currently, there is no direct way to write an object to a random access file.
But you can use the ByteArray input/output stream as an intermediary, to write to a random Access file or read bytes from a random Access file, and you can use a byte stream to create an object input/output stream for reading and writing objects. It is necessary to include a full object in the byte stream, Otherwise, an error occurs when reading and writing the object. For example, Java.io.ByteArrayOutputStream can be used to get a byte array of the ObjectOutputStream, from which you can get an octet and write it to a random access file. Instead, we can read out the byte array from the random Access file, It can construct the Bytearrayinputstream and construct the ObjectInputStream to read the object.

Ask:
When running RMI application, can you start the name service rmiregistry instead of manually, but from the program?

For:
OK. The Java.rmi package provides a class java.rmi.registry.LocateRegistry for getting the name service or creating a name service. Call Locateregistry.createregistry (int port) Method you can create a name service on a specific port so that users do not have to manually start Rmiregistry. In addition, the Locateregistry.getregistry (String host,int port) method can be used to obtain a name service.

Ask:
How do I set print properties such as printer names when using class PrintJob for print operations?

For:
Use the following method to obtain an instance of PrintJob to control the print operation:

Toolkit.getprintjob (Frame F, String JobTitle, Properties prop)

The settings for the print properties can be implemented by setting the properties of the prop, which include the following print properties:

Awt.print.destination: Can be "printer" or "file"

Awt.print.printer: Printer Name

Awt.print.fileName: Print file name

Awt.print.numCopies: Number of copies printed

Awt.print.options: Printing options for print commands

Awt.print.orientation: Print direction, can be "portrait" or "Landscape"

Awt.print.paperSize: Paper size, can be "letter", "legal", "executive" or "A4"

Ask:
The thread class defines the suspend () and resume () methods in JDK1.1, but it is obsolete in JDK1.2 and what methods should be used to replace them?

For:
Thread.Suspend itself is prone to deadlock. If a target thread locks a critical system resource and then the thread is suspend, then unless the thread is resume, Otherwise, other threads will not be able to access the system resource. If another thread will call resume to keep the thread running, and before that, it will need access to this system resource, then a deadlock is generated.

So, in Java 2, a more popular approach is to define the state variable for a thread and to poll the state variable, and then use the Wait () method when the state is suspended to keep it waiting. Once the thread is required to continue running, other threads call the Notify () method to notify it.

Ask:
Using JDBC programming, how should you control the pointer to the result set resultset so that it moves up and down, and moves to the first and last row of the result set?

For:
In JDK1.1, the next () method is defined in the ResultSet class to support the move of the data pointer. But in Java 2, the ResultSet class adds the following methods to support the movement of data pointers, including:

Resultset.first (): Moves the data pointer to the first row of the result set

Resultset.last (): Moves the data pointer to the last row of the result set

Resultset.previous (): Move the data pointer up one line

The above method is defined in the JDBC2.0 specification, and all JDBC drivers that support JDBC 2.0 can support this approach. Currently, JDBC driver vendors such as INTERSOLV and OpenLink have products that support JDBC 2.0.

Ask:
What kinds of Web servers support the servlet? How do I make IIS support the servlet?

For:
Currently, the server-side products that support the servlet include: Sun's Java webserver,lotus dominogo webserver,bea WebLogic Tengah Server,jigsaw,netforge, Acmeserver and MOT Bays jetty and so on.

In addition, a number of third-party vendors have developed servlet engine to enable other webserver (such as Netscape Web Server,iis, etc.) to run a servlet, such as Livesoftware JRun (http:// www.livesoftware.com/products/jrun/) and so on.

Ask:
How do I store images in an image file in a Java application?

For:
The Java Advanced Imaging API (contained in the Java Media API) allows for complex, high-performance image processing in Java applications. The JAI API provides the ability to store images. Currently, the JAI API supports the following image file formats: Bmp,jepg,png,pnm,tiff. A section of code that stores images in a BMP file is given below:


OutputStream OS = new FileOutputStream (Filetowriteto);

Bmpencodeparam param = new Bmpencodeparam ();

Imageencoder enc = imagecodec.createimageencoder ("BMP", OS, param);

Enc.encode (IMG);

Os.close ();

For a programming guide for storing image files, refer to the following pages:

http://java.sun.com/products/java-m...pers/jai-guide/

Ask:
How do I read and write data to a serial port in the Java language? Font>

For:
Sun's Java communication API2.0 can be used to read and write the serial port, which supports the RS232 serial port and the IEEE 1284 interface, providing a platform-independent string/port communication mechanism.

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.