Essential for programming: Java FAQ

Source: Internet
Author: User
Tags driver manager netscape web server

Q: How do I set the environment variables of Java 2 (jdk1.2?

A: After Java 2 is installed, you need to set the path and java_home environment variables. Different from jdk1.1: After setting the java_home environment variable, JVM will automatically search for the system class library and the current path of the user.

Java 2 environment variables are set as follows:
Solaris platform: installation path of setenv java_home Java2
Setenv path $ java_home/bin :$ {path}
Windows: installation path of set java_home = Java2
Set Path = $ java_homebin; % PATH %

Q: Which Java integrated development tools support Java 2?

A: currently, popular Java integrated development environments, such as Inprise's JBuilder, Symantec's visual cafe, and Sybase's powerj, all support Java 2.

Q: If an error occurs when running a Java Applet in Netscape or IE browser, how can I determine the error range?

A: When a Java Applet runs in a browser, the default JVM of the browser is used. different browsers have different levels of support for JDK. therefore, an error occurs when running a Java Applet in Netscape or IE. We recommend that you use the JDK tool appletviewer or Sun's hotjava browser to test the applet, to determine whether the error is caused by a browser.
  
If the applet runs normally in appletviewer or hotjava, the error occurs because the browser is not fully compatible with JDK. the solution can be to use the hotjava browser or install Sun's Java Plugin.
If the applet runs in the hotjava browser or appletviewer, an error occurs. Check the applet according to the error prompt.

Q: Why do Chinese characters sometimes show garbled characters when JDBC is used to insert data into or extract data from the database?

A: The implementation of this problem is usually related to the implementation of each JDBC driver. currently, most JDBC drivers use local encoding formats to transmit Chinese characters. For example, Chinese characters "0x4175" are converted to "0x41" and "0x75" for transmission. therefore, we need to convert the characters returned by the JDBC driver and the characters to be sent to the JDBC driver.

When you use JDBC driver to insert data to a database, you need to convert Unicode to native code first. When the JDBC driver queries data from the database, you need to convert the native code to Unicode. the implementation of these two conversions 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 the preceding two methods, some JDBC drivers do not need to set correct character set attributes for JDBC driver manager.

Q:
When servlet is used to process HTTP requests and generate returned HTML pages, how can the Chinese characters in the HTML pages be properly displayed?

A:
Javax. servlet. HTTP. the httpresponse class is used to generate a response page. you can use the getoutputstream () method defined by httpresponse to obtain the instance of servletoutputstream, so that you can use servletoutputstream. the write method writes the content of the returned page to the output stream. however, servletoutputstream uses the default encoding method. To enable normal display of text characters on the returned page, it is best to specify the encoding method. generally, you need to construct an outputstreamwriter. The routine is 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 a test ");

Ow. Flush ();

Ow. Close ();

}

Q:
How to set the Java webserver classpath to include the user's class file?

A:
You can set the classpath environment variable of Java webserver in two ways, so that the servlet compiled by the user can call the class file of the user.
Put your class file in the javawebserver_dir/classes directory. When Java webserver is started, the classes directory is automatically added to the classpath environment variable.
Modify the httpd. nojre file and add the path name of the user class file to the classpath environment variable.

Q:
Why is it slow to obtain remote RMI objects using naming. lookup on windows?

A:
An incorrect network configuration may cause this problem.
RMI uses Java Network classes, especially java.net. inetaddress class, which queries the TCP/IP host name, including IP address-to-host ing and host-to-IP address ing. on Windows, this query function is implemented by the local Windows Socket library. therefore, the latency occurs in the Windows library, not in RMI.

If your machine is set to use DNS, the problem is that the DNS server cannot find the host name, And the latency you find is the latency of DNS query. add all host names/IP addresses involved in RMI communication to the local file winntsystem32driversetchosts or windowshosts. the format is as follows:

IP address Host Name

This setting should significantly reduce the query time.

Q: How do I set proxy information when writing a Java application to access an external website?

A:
If you access an external website in Java application, set the proxy information first. 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 jlist data of the swing component has been modified. How can I notify the jlist to change the display?

A:
The jlist component has a separate display mode listmodel to represent the jlist display data.
After jlist is created, the value of jlist data elements and the number of data elements can be dynamically changed.
Jlist observes data changes in its data mode listmodel. Therefore, the correct implementation of a listmodel should notify the event listener every time the data changes.
When you use the constructor jlist (object []) to create a jlist instance, the system automatically creates an defaultlistmodel instance to store the display data of jlist, you can call the simple method defined in defalistlistmodel to dynamically modify jlist data, such as removeelementat (INDEX) and addelement (object. defaultlistmodel notifies the jlist of data changes while modifying data.

Q:
How to implement a mode dialog box in Java Applet?

A:
The key to implementing the mode dialog box in Java applet is to specify a correct parent window for the dialog box when creating a dialog box. because the applet is a subclass of the Panel class and cannot be used as the parent window of the dialog box, you must first obtain the window of the Applet as the parent window of the mode dialog box. the sample code is as follows:

.....

Dialog d = new dialog (getparentwindow (COMP), title );

// Comp is any component of 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 can I display another HTML page in a Java Applet?

A:
The appletcontext and appletcontext. showdocument (URL) methods related to the applet can be obtained through the java. Applet. Applet. getappletcontext () method to display another webpage in the browser where the applet is located.

Q:
Can I run the signature applet implemented by JDK in Netscape or IE?

A:
The signature applet implemented by JDK cannot be run in Netscape or IE, but can be run in hotjava browser.

Different browsers provide different signature applet mechanisms. For example, Netscape provides the zigbert tool and capability API, while ie uses the cab file. however, neither the signature applet generated by the Netscape tool nor the signature applet generated by IE can be run in other browsers.

To enable the JDK signature applet to run in Netscape or IE, install Java Plugin in Netscape or IE, then, the signature applet implemented by JDK can be run in these two browsers.

Q:
The JNI technology can be used to call the C library from a Java application. But how can this C library call another C library?

A:
If a C library C1 called by Java still needs to call another C library C2, it should be connected to library C2 when compiling C1. The steps are as follows (Solaris platform ):
Compile and compile the Java file that calls the C library.
Javac Java file name

Generate C program header file
Javah-JNI Java file name (without the suffix. Java)

Compile and compile the C program c1.c called by Java and c2.c called by C1.
CC-g-iinclude pathname c2.c-O libc2.so
CC-g-iinclude pathname-LC2 c1.c-O libc1.so

Set Environment Variables
Setenv LD_LIBRARY_PATH libc1.so, path of libc2.so
:$ {LD_LIBRARY_PATH}

Run a Java application

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

A:
In Java 2, the file class in the Java. Io package adds the listroots () method to implement this function.

Q:
Is runtime.exe C ("ls") without any output?

A:
Call the runtime.exe C method to generate a local process and return an instance of the Process subclass. This instance can be used to control the process or obtain information about the process. since the sub-process created by calling the runtime.exe C method does not have its own terminal or console, the standard io (such as stdin, stdou, stderr) of the sub-process passes the process. getoutputstream (), process. getinputstream (), process. the geterrorstream () method is redirected to its parent process. you need to use these streams to input data to the sub-process or obtain the output of the sub-process. the example that executes runtime.exe C ("ls") in the worker is as follows:

Try

{

Process = runtime.getruntime(cmd.exe C (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 ());

}

Q:
How to generate a signature applet so that the applet can access local resources?

A:
In jdk1.1, you can use the javakey command to generate a jar file with public keys, private keys, certificates, and signatures. For more information, see http://java.sun.com/security/usingjavakey.htmland Java 2 to greatly improve the signature mechanism, allows users to set security permissions more flexibly. java 2 provides three tools: keytool, policytool, and jarsigner to implement the signature applet. for example, Joe compiled a signature Applet: signedapplet. java, the process of generating a simple signature applet is as follows:

 

// Generate a key. The key alias is Joe and the password is sign12, which is stored in the key store joestore.

Keytool-genkey-alias Joe-keypass sign12-keystore joestore

// Package signedapplet. Class and related files into jar files

Jar CVF signedappletdemo. Jar

// Use the self-signed certificate generated by keytool to generate the signature applet (JAR file)

Jarsigner-keystore joestore-signedjar Joe. Jar signedappletdemo. Jar Joe

// Output the self-signed certificate from the keystore to the file

Keytool-export-keystore joestore-alias Joe-file Joe. Cer

For the receiver of the signed applet, Susan needs to perform the following steps safely:

Signature applet compiled by Joe:

// Obtain the Joe certificate and read it into the susanstore in the keystore

Keytool-import-alias Joe-file Joe. cer-keystore susanstore

// Run policytool to generate a policy file that meets Susan's requirements

Yytool

// Run it with appletviewer or install Java Plugin in the browser.

For details about how to deploy the signature Applet in Java Plugin, refer to the following webpage:

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

Note: For simplicity, the self-signed certificate generated by keytool is used. In fact, you can also

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

Q:
If you use objectoutputstream to write objects to an object multiple times in append mode, why does streamcomputedexception occur when you use objectinputstream to read these objects?

A:
When the default serializetion is used, the construction of an objectoutputstream and the construction of an objectinputstream must correspond one to one. the objectoutputstream constructor will write an ID header to the output stream, and objectinputstream will first read this ID header. therefore, when an object is written to a file in append mode multiple times, the file will contain multiple identification headers. so when objectinputstream is used to deserialize this objectoutputstream, streamcomputedexception will be generated. one solution is to construct a subclass of objectoutputstream and overwrite the writestreamheader () method. the overwritten writestreamheader () method should determine whether to write the object to the file for the first time, writable? Super. writestreamheader () is called. If no, the objectoutputstream. Reset () method should be called when the object is written in append mode.

Q:
The object serialization class is stream-oriented. How should I write the object into a random access file?

A:
Currently, there is no direct way to write objects to random access files.
However, bytearray input/output streams can be used as an intermediary to write data to random access files or read data from random access files. byte streams can be used to create object input/output streams, to read and write objects. note that a complete object must be included in the byte stream; otherwise, an error will occur when reading and writing the object. for example, Java. io. bytearrayoutputstream can be used to obtain the byte stream of objectoutputstream, from which the byte array can be obtained and written to the random access file. on the contrary, we can read byte arrays from random access files and use them to construct bytearrayinputstream to construct objectinputstream to read objects.

Q:
Can I start the name service rmiregistry from the program instead of manually starting the RMI application?

A:
Yes. java. the RMI package provides a class of Java. RMI. registry. locateregistry, used to obtain a name service or create a name service. call locateregistry. the createregistry (INT port) method can create a name service on a specific port, so that you do not need to manually start rmiregistry. in addition, locateregistry. the getregistry (string host, int port) method can be used to obtain the name service.

Q:
How do I set print attributes such as the printer name when I use a printjob-like printing operation?

A:
Use the following method to obtain the printjob instance to control the print operation:

Toolkit. getprintjob (frame F, string jobtitle, properties prop)

You can set the print attributes by setting the properties of prop. The print attributes include:

AWT. Print. Destination: can be "Printer" or "file"

AWT. Print. printer: printer name

AWT. Print. filename: print the file name

AWT. Print. numcopies: Number of copies

AWT. Print. Options: Print option of the print command

AWT. Print. Orientation: Print direction, which can be "portrait" or "Landscape"

AWT. Print. papersize: paper size, which can be "letter", "legal", "executive" or "A4"

Q:
In jdk1.1, the thread class defines the suspend () and resume () methods, but it is outdated in jdk1.2. What method should be used to replace it?

A:
Thread. suspend itself is prone to deadlock. if a target thread locks a key system resource and the thread is suspend, other threads will not be able to access the system resources unless the thread is resume. if another thread calls resume to continue running, and before that, it also needs to access this system resource, a deadlock will occur.

Therefore, in Java 2, the popular method is to define the state variable of the thread and make the target thread poll the state variable. When the State is suspended, you can use wait () method to make it in the waiting state. once the thread needs to continue running, other threads will call the notify () method to notify it.

Q:
In JDBC programming, how should we control the pointer of the result set resultset so that it can be moved up or down, and to the first and last rows of the result set?

A:
In jdk1.1, The resultset class only defines the next () method to support data pointer moving down. However, in Java 2, The resultset class adds the following methods to support data pointer moving, including:

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

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

Resultset. Previous (): Move the Data Pointer up a row

The preceding method is defined in the jdbc2.0 specification. All JDBC drivers supporting JDBC 2.0 support the preceding method. Currently, JDBC drivers such as intersolv and openlink support JDBC 2.0.

Q:
Which Web servers support servlets? How to Make IIS support Servlet?

A:
Currently, servlet-supported Server products include sun's Java webserver, Lotus dominogo Webserver, BEA WebLogic Tengah server, Jigsaw, netforge, acmeserver, and MOT bays jetty.

In addition, some third-party vendors have developed servlet engines to enable other webservers (such as Netscape Web server, IIS, etc.) to run Servlets, such as livesoftware's JRun (http://www.livesoftware.com/products/jrun /) and so on.

Q:
How to store images to image files in Java applications?

A:
Java advanced imaging API (included in java media API) allows complex and high-performance image processing in Java applications. jai APIs provide image storage capabilities. currently, Jai API supports the following image file formats: BMP, jepg, PNG, PNM, And Tiff. the following code stores an image to a BMP file:

Outputstream OS = new fileoutputstream (filetowriteto );

BMP encodeparam Param = new BMP encodeparam ();

Imageencoder ENC = imagecodec. createimageencoder ("BMP", OS, Param );

ENC. encode (IMG );

OS. Close ();

For the programming guide for storing image files, see the following webpage:

Http://java.sun.com/products/java-media/jai/forDevelopers/jai-guide/

Q:
How can I read and write data to the serial port in Java? Font>

A:
Sun's Java communication api2.0 can be used for reading and writing serial ports. It supports RS232 serial ports and IEEE 1284 parallel ports, and provides a platform-independent serial/parallel communication mechanism.

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.