Java FAQ highlights from Sun Chinese official site

Source: Internet
Author: User
Tags driver manager netscape web server object serialization
Java FAQ highlights are from Sun's Chinese official website-general Linux technology-Linux programming and kernel information. The following is a detailed description. Q: How do I set the environment variables of Java 2 (JDK1.2?
A:
?? After installing Java 2, 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 JBuilder, Symantec's Visual Cafe, and Sybase 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 java applet runs in the 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 using Servlet 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 do I 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") not 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 can I 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 deployment of signature applet in Java Plugin, see the following web page: 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, but ByteArray input/output streams can be used as the intermediary, to write data to or read data from random access files. You can use byte streams to create object input/output streams for reading and writing 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 rmiregistry service 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 methods 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: How can I control the pointer of the result set ResultSet for JDBC programming 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 can I store images in 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/jav... velopers/jai-guide/

Q: How can I read and write data to the serial port in Java?
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.