Java common problem highlights 25 questions

xiaoxiao2021-03-04  50

1 Search system class libraries and user's current path. The setting of Java 2 Environment variables As shown in the following example: Solaris platform: STENV Java_home Java2 installation path setenv path $ java_home / bin: $ {pat} Windows platform: set java_home = java2 installation Path SET PATH = $ java_homebin;% PATH% 2, Q: What Java integrated development tools support Java 2? A: The current popular Java integrated development environment, such as Inprise's JBuilder, Symantec's Visual Cafe, Sybase's Powerj, support Java 2. 3, Q: If there is an error when running the Java applet in the Netscape or IE browser, how to determine the error range? A: When the Java Applet is running in the browser, use the browser itself's default JVM. Different browsers have different levels of support for JDK. Therefore, running Java Applets in Netscape or IE browsers, it is recommended to use JDK supplied tool AppletViewer or Sun's Hotjava browser to test the applet. Determining the error is related to the browser. If the applet runs everything in AppletViewer or HotJava, the error is caused by the browser is not fully compatible with JDK. At this point, the solution can be used in the use of HotJava browser or installation Sun's Java Plugin. If the applet runs in the Hotjava browser or AppletViewer, the Applet program should be checked according to the error prompt. 4. Q: When using JDBC to insert data into the database or extract data from the database, why Sometimes Chinese characters will be garbled? A: This issue is usually related to the implementation of each JDBC Driver. At present, most JDBC Driver uses local coding format to transmit Chinese characters, such as Chinese characters "0x4175" will be converted to "0x41" And "0x75" is transmitted. Therefore, we need to convert characters returned by JDBC Driver and transition to JDBC Driver. When using JDBC DRIVER to the database When inserted into data, you need to transfer Unicode to Native Code; when you query data from the database, you need to convert Native Code into unicode. The implementation of these two conversions is given: String Native2Unicode (String s) {IF (s == null || s.LEngth () == 0) {Return Null;} Byte [] buffer = new byte [S.Length ()]; for (int i = 0; i s.ley ); 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 two methods, some JDBC Driver If the correct character set properties are set to JDBC Driver Manager, the above 2 methods are not needed. 5, Q: When using servlet to process HTTP requests and return When the HTML page, how to make the Chinese characters in the HTML page can display properly? A: javax.servlet.http.httpResponse class is used to generate return pages. GetOutputStream () can get the instance of servletoutstream () by httpResponse-definition method, so that users can Write the contents of the return page in the output stream using the servletoutputstream.write method. But servletOutputStream uses the default encoding method. If you want to make the Chinese characters in the return page can be displayed normally, it is best to specify the character encoding used. usually need to construct a OutputStreamWriter, routine 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 test"); OW.Flush (); OW.Close ();} 6, Q: How to set the ClassPath of Java WebServer to include the user's class file A: There are two ways to set the ClassPath environment variable of Java WebServer to use the servlet written by the user to call the user's class file. Place the user's Class file in the JavaWebser_Dir / Classes directory, Classes catalog when Java Web Server starts Automatically added to the ClassPath environment variable. Modify the httpd.nojre file, add the path name where the user class file is located to the ClassPath environment variable. 7, ask: Why use naming.lookup on the Windows platform to get far When the RMI object is very slow? A: The machine's network settings are incorrectly probably caused by this problem. RMI uses Java network classes, especially the java.net.inetaddress class, which will query the host name of TCP / IP Maps and hosts, including the IP address to the hostname. In the Windows platform, this query function is implemented by the local Windows Socket library. So the delay is in the Windows library, not RMI In. If your machine is set to use DNS, the problem is usually the DNS server can't find the host name. The delay you find is the delay of the DNS query. Please try to put all hostname / IP addresses involved in RMI communication Add to local files WinntSystem32driverseetstetchosts or WindowsHosts. The format is as follows: IP address hostname should significantly reduce the time spending the query. 8, ask: How to set up the Java Application to access the external website? Answer : If you access the external website in Java Application, you should first set up proxy information, sample code as follows: import java.util.properties; ..... Properties Sys = system.getproperties (); sys.put ("proxyset", "true"); sys.put ("proxyhost", "myhtp.proxyserver.com); sys.put (" proxyport "," 80 "); system.setproperties (sys); u =

New url; connection = (httpurlconnection) u.openconnection (); ..... 9, ask: Swing component jlist's list data modified, how to inform JList change display? A: Jlist component has a separate display Mode ListModel is displayed in Jlist. Jlist is created, the value of JList data elements and the number of data elements can be dynamically changed. Jlist Observe data changes in its data mode ListModel. Therefore, a ListModel's correct implementation should be When each data changes, the listener of the event is notified. When using the constructor jlist (Object []), a DEFAULTLISTMODEL is automatically created to store the display data of JLIST, which can call the DEFAULTLISTMODEL A simple way to dynamically modify the JList's data, such as RemoveElementat (INDEX), AdDelement (Object), etc. DEFAULTLISTMODEL will notify Jlist About data from data while modifying data. 10, ask how to implement a pattern in Java Applet Dialog • A: The key to implement the mode dialog box in the Java applet is to specify a correct parent window for the dialog when you create a dialog. Because Applet is a subclass of the Panel class, it is not a dialog box. The parent window, so you first get the window where the applet is located, as the parent window of the Mode dialog. Sample code is as follows: ..... Dialog D = New Dialog (getParentWindow (Comp), Title); // CoMP is on the applet Any component .... public void getParentWindow (Component Componpplet, String Title) {Container C = ComponApplet.getParent (); while (c! = Null) Return (Frame) C = C.GETParent ();} return null;

} 11, ask: How to display another HTML page in the Java applet? A: You can get the appletContext () method to get the applet, appletContext.ShowDocument (URL) method associated with the applet, applying. The browser displays another web page. 12, ask: Can you run the signature applet with JDK, can you run in Netscape or IE? A: Use the JDK-implemented signature applet, you cannot run in Netscape or IE, but you can browse in Hotjava Run in the gear. Different browsers provide different signature Applet mechanics, such as Netscape provides Zigbert tools and Capability APIs, and IE requires the use of CAB files. However, whether the signature generated by the Netscape tool is generated, or use IE Signing Applets can not be run in other browsers. If you want to make JDK generated signature Applets can run in Netscape or IE, the solution is to install Java Plugin in Netscape or IE, the signature applet implemented with JDK You can run in both browsers. 13. Q: Use JNI technology to call the C library from the Java application, but how to make the C library can call another C subscription? A: If a Java is called by Java The C library C1 still needs to call another C library C2, then connect the library C2 when compiling C1, the steps are as follows (Solaris Platform): Write the Java file calling the C library, compile. Javac Java file name to generate C The program header file javah -jni java file name (without suffix .java) Written the C program C1.c called by Java, and C2.c called C1, and compiled. Cc -g -iinclude path name C2.c o libc2.so cc -g -iinclude path name -lc2 c1.c -o libc1.so Set the environment variable Stenv ld_library_path libc1.so, libc2.so location path: $ {ld_library_path} Run Java Application 14, Q: In Java Language How to list all the drive names in the PC file system? A: In Java 2, the File class in the java.io package adds method Listroots () to achieve this function. 15, ask: What runtime.exec ("ls") does not have any output? A: Call the runtime.exec method will generate a local process and return an instance of a process subclass, which can be used to control the process or acquire the process. Call the child process created by the runtime.exec method No end or console, so the standard IO (such as stdin, stdou, stderr) is process.getoutputstream (), process.GetErrorStream () () The method is redirected to the parent process. The user needs to use these stream to enter data or get the output of the child process to the child process. So correct execution of runtime.exec ("ls") is 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 ());

} 16, ask: How to generate a signature applet to enable Applet to access local resources? A: In JDK1.1, you can use the javakey command to generate public keys, private keys, certificates, and signature JAR files, please refer to: Http://java.sun.com/security/usingjavakey.html and Java

2 Among the signature mechanisms, allow users to set security more flexibly. Java 2 provides three tools: KeyTool, PolicyTool, and Jarsigner to implement signing applet. For example, Joe has written a signature applet: signedapplet.java Then generate a simple signature applet is as follows: // Generate a key, the key is not named Joe, the password is SIGN12, stored in keytool -genkey-ittore joe -keypass sign12 -keystore joestore // Signedapplet.class and related files are packaged into JAR file JAR CVF SIGNEDAPPLETDEMO.JAR / / The self-signed certificate generated by KeyTool generated a signature applet (JAR file) jarsigner -keystore joesteore -signedjar joe.jar SignedappletDemo.jar JoE // Self-signature The certificate is output from the keystore to the file keytore -elias joe-ready joe.cer and the acceptor Susan for the signature applet, you need to securely perform the Joe written by JoE by securely perform JoE's certificate: // Get JoE certificate And read it into the keytore -import -alias joe -file joe.cer-ittore sue -file joe.cer -keystore sue -filetore to generate the policy file policytool // run with AppletViewer, or in the browser Install Java Plugin to run. For the deployment of the signature applet in Java Plugin, please refer to the following page:

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

Note: The above example is simply, using the self-signed certificate generated by KeyTool. In fact, the user can apply for an e-certificate to the commercial CA center using KeyTool-Cautreq. 17, Q: If the ObjectOutputStream is multiple times in a file to a file write object way, why have StreamCorruptedException when reading these ObjectInputStream object with? a: when you use the default serializetion achieve, and a construction ObjectOutputStream and ObjectInputStream must construct a one-.ObjectOutputStream the constructor to the output stream Write a marking head, while ObjectInputStream first reads this identity head. Therefore, when writing to Object multiple times, the file will contain multiple identification heads. So use ObjectInputStream to deserialize this ObjectOutputStream When the STREAMCORRUPTEDEXCEPTION will be generated. One solution is a subclass of ObjectOutputStream and overrides the WriteStreamHeader () method. The written WriteStreamHeader () method should determine whether to write Object in the file for the first time, CA. Super.WriteStreamHeader (); if you write Object, you should call the objectOutputStream.Reset () method. 18, ask: The serialization class is a flow-oriented, how to write objects Enter a random access file? A: Currently, there is no direct method to write objects into a random access file. But you can use the ByteArray input / output stream as an intermediary to write or from the random access file. The use of the byte in the file, and you can use byte flow to create an object input / output stream for reading and writing. Need not to note that in the byte stream, you need to include a complete object, otherwise read and write An error will occur when the object is, for example, Java.io.byteArrayoutputStream can be used to get the byte stream of ObjectOutputStream, which can be obtained from the Byte array and can be written to the random access file. Instead, we can be from the random access file Read the byte array, use it to construct ByteArrayInputStream, and thus construct ObjectInputStream to read Object. 19, ask: When running RMI applications, you can not start the name service RMIREGISTRY, but start from the program? A: Yes. Java.rmi package provides class java.rmi.Rmi.Rmi.LocateRegistry, used for Get the name service or create a name service. Call the locateregistry.createRegistry (int port) method can create a name service at a particular port, so that users do not need to manually start RMIRGISTRY. In addition, LocateRegistry.getRegistry (String Host, int port) method can be used Get the name service. 20, ask: How should I set the printing attributes such as the printer name using class printjob? A: Use the following method to get PrintJob instance to control print operation: Toolkit.getPrintJob (frame F, String jobtitle The Properties Pro will be implemented by setting the Print property settings, printed attributes include: aff.print.destination: may be "printer" or "file" aff.print.printer: printer name AWT.PRINT .filename: Print file name AWT.PRINT.NUMCOPIES: Costs AWT.PRINT.Options: Print command print options AWT.PRINT.ORIATATION: Print direction, can be "portrait" or "landscape" aff.print.papersize: Paper size, can be "letter", "legal", "

Executive "or" a4 "21, Q: The thread class in JDK1.1 defines the suspend () and the resume () method, but it is already in JDK1.2, what method should be used instead? A: thread.suspend It is easy to generate a deadlock. If a target thread is locked for a key system resource, then the thread is SUSPEND, then other threads will not be able to access the system resources unless the thread is resume, other threads will not be able to access the system resource. If another thread The resume will be called so that the thread continues to run, and before this, it also needs to access this system resource, which will result in a deadlock. Therefore, in Java 2, a popular way is to define the status variable of the thread, and make The target thread polls the status variable. When the status is a suspension state, the WAIT () method can be used in the waiting state. Once the thread is required to continue to run, the other thread calls the notify () method to inform it. 22, Q: Use JDBC programming, how to control the result set Resultset's pointer, so that it can move up and down, and move to the first row and last row of the result set? A: In JDK1.1, only NEXT () method is defined in the ResultSet class. Support the down movement of the data pointer. But in Java 2, the ResultSet class adds the movement of the data pointer, including: resultT.First (): Move the data pointer to the first line of the result set ResultSet.last (): Move the data pointer to the last line of the result set. ResultSet.Previous (): Move the data pointer to the method defined in the JDBC2.0 specification, all JDBC drivers that support JDBC 2.0 can support the above method. Current INTERSOLV JDBC driver manufacturers such as OpenLink support JDBC 2.0. 23, ask: Which Web Server supports servlet? How to make IIS support servlet? A: Currently, Servlet server-side products mainly include: Sun Java Web Server , Lotus Domino Web Server, Jigsaw, Netforge, Acmeserver and Mot Bays Jetty. In addition, some third-party manufacturers have also developed servlet engine to enable other WebServer (such as Netscape Web Server, IIS, etc.) to run servlet. Such as LiveSoftware's JRun (http: // www. LiveSoftware.com/

Products / JRUN /), etc. 24, ask: How to store images into image files in Java applications? A: Java Advanced Imaging API (included in Java Media API) Allows complex, high performance in Java applications Image processing .JAI API provides the ability to store images. Currently, JAI API supports the following image file formats: BMP, JEPG, PNG, PNM, Tiff. The following is given below a piece of code to store images to BMP files: OutputStream OS = new FileOutputStream (fileToWriteTo); BMPEncodeParam param = new BMPEncodeParam (); enc.encode (img);; os.close (); For the programming for storing image files ImageEncoder enc = ImageCodec.createImageEncoder ( "BMP", os, param) Guide, please refer to the following page:

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

25, ask: How to read and write data to serial port in Java language? A: Sun's Java Communication API2.0 can be used to read and write serial ports, which supports RS232 serial port and IEEE 1284 parallel port, providing a string / parallel port-independent of platform Communication mechanism.

转载请注明原文地址:https://www.9cbs.com/read-31643.html

New Post(0)