Programming | questions
Q: How do I set the environment variables for Java 2 (JDK1.2)?
A: After installing Java 2, 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: setenv java_home Java2 Installation path setenv path $JAVA _home/bin:${path} Windows platform: set JAVA _HOME=JAVA2 installation path set path= $JAVA _homebin;%path%
Q: Which Java integrated development tools support Java 2?
A: The current popular Java integrated development environment, such as Inprise's Jbuilder,symantec visual Cafe, Sybase Powerj, supports Java 2.
Q: If there is an error running Java applets in Netscape or IE browsers, how do you determine the error range?
A: When Java applets 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.
Q: When using JDBC to insert data into a database or extract data from a database, why do Chinese characters sometimes appear garbled?
A: 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.
Q: 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?
A: 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 ();
}
Q: How do I set the Java webserver classpath to contain the user's class file?
A: 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.
Q: Why is it slow to get remote RMI objects with Naming.lookup on the Windows platform?
A: The incorrect network settings of the machine may 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?
A: If you are accessing an external Web site in the Java application, you should first set proxy information, the sample code is as follows:
Q: The Swing component JList list data has been modified, how to notify the JList change display?
A: 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.
Q: How do I implement a modal dialog box in Java applets?
Answer: 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?
A: The Java.applet.Applet.getAppletContext () method allows you to obtain the Appletcontext, Appletcontext.showdocument (URL) associated with this applet method to display another Web page in the browser that the applet is in.
Q: Can a signed applet implemented with JDK run in Netscape or IE?
A: 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.
Q: Using JNI technology to invoke the C program library from a Java application, but how do you make the C program library call another C program library?
A: If a Java-invoked C-Library C1 still needs to invoke another C-Library C2, then you should join the library C2 when compiling C1, as follows (Solaris platform): Write Java files that invoke the C library and compile them. 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 pathname-lc2 c1.c-o
Set environment variable setenv ld_library_path libc1.so,libc2.so path: ${ld_library_path}
Running Java applications
Q: In the Java language, how do I list all the drive names in the PC file system?
A: In the Java 2 version, the file class in the Java.io package adds a new method Listroots () to implement this functionality.
Q: Why is runtime.exec ("LS") without any output?
A: Invoking 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:
Q: How do I generate a signed applet to enable the applet to access local resources?
A: In jdk1.1, you can use the Javakey command to generate public keys, private keys, certificates, and signed 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
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.
Q: If you write object more than once in a file by ObjectOutputStream, why does it produce streamcorruptedexception when you read the object with ObjectInputStream?
A: 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.
Q: Object serialization (serialization) class is stream-oriented, how should the object be written to a random access file?
A: At present, 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.
Q: When running RMI application, can you not manually start the name Service Rmiregistry, but start from the program?
Answer: Yes. 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.
Q: How do I set print properties such as printer names when using class PrintJob for print operations?
A: You can use the following methods to obtain an instance of PrintJob to control print operations:
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"
Q: 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?
A: 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.
Q: Using JDBC programming, how do 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?
A: 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.
Q: What kinds of Web servers support the servlet? How do I make IIS support the servlet?
A: Currently, the server-side products that support the servlet include: Sun's Java webserver,lotus dominogo webserver,bea WebLogic Tengah Server,jigsaw,netforge,ac Meserver 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.
Q: How do I store images in an image file in a Java application?
A: 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 ();
Q: How to read and write data to a serial port in the Java language? Font>
A: Sun's Java communication API2.0 can be used to read and write serial ports, it supports RS232 serial port and IEEE 1284 interface, and provides a platform-independent string/port communication mechanism.
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.