Java common problem highlights

xiaoxiao2021-03-06  67

Java common problem highlights

How to set up the environment variable of Java 2 (JDK1.2)? Which Java Integrated Development Tools support Java 2? If you have errors when running a Java Applet in the Netscape or IE browser, how to determine an error range? Insert to the database with JDBC When data is extracted from the database, why is the Chinese characters display as garbled? When using servlets to process HTTP requests and generate returned HTML pages, how to make the Chinese characters in the HTML page normal display? How to set up Java Web Server ClassPath to include the user's class file? Why use naming.lookup on a Windows platform to get a remote RMI object? How to set up the Java Application to access the external website? Swing component Jlist display data Modify, how to inform JList change display? How to implement a mode dialog box in the Java applet? How to display another HTML page in the Java Applet? Signature Applet implemented with JDK, can you run in Netscape or IE? Can I use JNI technology? Call the C library from the Java application, how to make the C library can call additional C libraries? How to list all drive names in the PC file system in the Java language? Why Runtime.exec ("ls" No output? How to generate signage applets to enable Applet to access local resources? If you use ObjectOutputStream to write Object multiple times in a file, why use ObjectInputStream to read these Object Sequences Sequence? (serialization) The class is for streaming. How should I write objects to a random access file? When running the RMI application, can you not manually start the name service RMIRGISTRY, but start from the program? Using the class printjob for printing operations How should I set the printer name and other print properties? The thread class in JDK1.1 defines the suspend () and resume () methods, but what is the way to use in JDK1.2, what method should be used instead? Use JDBC programming, How to control the results set Resultset's pointer, allow it to move up and down, and move to the first row of the result set and the last line? Which Web Server supports servlet? How to make the IIS support servlet? How to store image in the Java app Go to the image file?

How to use the Java language to read and write data to the serial port? Q: How to set the environment variable of Java 2 (JDK1.2)? A: Java 2 After installation, you need to set the PATH and JAVA_HOME environment variables. Different from JDK1.1: Set good After the Java_Home environment variable, JVM will automatically search system class libraries and user's current path. The setting of Java 2 Environment variables As shown in: Solaris Platform: STENV Java_Home Java2 installation path setenv path $ java_home / bin: $ {path} Windows Platform: Set java_home = Java2 installation path set path = $ java_home / bin;% PATH% Q: What Java integrated development tools support Java 2? A: The popular Java integrated development environment, such as the JBuilder of Inprise, Symantec Visual Cafe , Sybase's Powerj supports Java 2. Q: If you have an error when running a Java applet in the Netscape or IE browser, how do I determine an error range? A: When the Java Applet is running in the browser, use a browser The default JVM in itself is different. Different browsers have different support for JDK. Therefore, running Java Applets in Netscape or IE browser, it is recommended to use the tools provided by JDK AppletViewer or Sun's Hotjava browser To test the applet to determine the incorrect generation 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 time, the solution can be Use the Hotjava browser or install Sun's Java Plugin. If the applet runs in the HotJava browser or AppletViewer, you should check the Applet program based on the error prompt. Q: Use JDBC to insert data into the database or extract from the database When data is displayed as 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 turned "0x41" and "0x75" are transmitted. So we need the characters returned to JDBC Driver and to send to JDBC Driver's character conversion. When you insert data to the database with JDBC Driver, you need to transfer Unicode to Native Code; when you query data from the database, you need to convert Native Code into unicode. Below these two Implementation of conversion: 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 two methods, some JDBC Driver is set correctly for JDBC Driver Manager The character set properties, the above 2 methods are not needed. Q: When using servlets to process HTTP requests and generate returned HTML pages, how to make the Chinese characters in the HTML page normal display? A: javax.servlet.http The .httpResponse class is used to generate return pages. GetOutputStream () can get an instance of servletOutputStream (), so that users can use the servletoutPutStream.Write method to write to the output stream. But servletOutputStream uses default The encoding method, if you want to make the Chinese characters in the return page, it is best to specify the character encoding method used. It is often necessary to construct an OutputStreamWriter, the routines are 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 (); oclose ();} Q: How do I 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 enable the servlet written by the user. Call the user's class file. Place the user's Class file in the javawebser_dir / classes directory, when the Java Webserver starts, the class directory is automatically added to the ClassPath environment variable. Modify the httpd.nojre file, the path where the user class file is located Adding to the ClassPath environment variable. Q: Why use naming.lookup on the Windows platform to get the remote RMI object is slower? A: The machine's network setting is incorrectly probably caused by this problem. RMI uses Java Network class, especially Java.Net.inetaddress classes, which will query the host name of TCP / IP, including the IP address to the host name mapping and host name to the IP address. In the Windows platform, this query function is made by local The Windows Socket library is implemented. So the delay is in the Windows library, not in the RMI. If your machine is set to use DNS, the problem is usually the DNS server can't find the host name, and what you find is the latency DNS query delay. Please try to add all hostname / IP addresses involved in RMI communication to local file / winnt / system32 / drivers / etc / hosts or / windows / hosts. The format is as follows: IP address host name Settings should significantly reduce the time spending the query. Q: How to set up proxy when writing Java Applications In order to access the external website? A: If you access the external website in Java Application, you should first set the 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: Swing component jlist's list data is modified, how to notify JList change display? A: Jlist component has a separate display mode ListModel to represent Jlist's display data. After creation, the value of jlist data elements and The number of data elements can dynamically change. Jlist's observation of data changes in its data mode ListModel. Therefore, a ListModel's correct implementation should notify the event's listener when each data is changed, when using constructor Jlist ( Object []) When you create an instance of a JList, the system will automatically create an instance of a DEFAULTLISTMODEL to store JLIST display data, which can call the simple way defined in DefaultListModel to dynamically modify the JList data, such as RemoveElementat (INDEX), AdDelement ( Object), etc. DEFAULTLISTMODEL will notify Jlist for data changes while modifying data. Q: How do I implement a mode dialog box in the Java applet? A: The key to implementing the mode dialog box in the Java applet is to create a dialog When you want to specify a correct parent window for the dialog. Because Applet is a subclass of the Panel class, you cannot use the parent window of the dialog, so you first get the window where the applet is located, the parent window of the mode dialog. Sample Examples are as follows: ..... Dialog D = New Dialog (getParentWindow (Comp), title); // CoMP is any component 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 to display another HTML page in the Java applet? A: You can get the appletContext () method to make the applet to browse the applet () method through the java.applet.applet.getappletcontext () method. Displays another web page. Q: Can I run with JDK implementation, can I run in Netscape or IE? A: The signature applet implemented with JDK can not be run in Netscape or IE, but can run in the Hotjava browser. Different browsers provide different signature Applet mechanisms, such as Netscape provides Zigbert tools and Capability APIs, while IE requires using a CAB file. However, whether it is the signature applet generated by the Netscape tool, or the signature APPPlet generated by IE, You cannot run in other browsers. If you want to make the JDK generated signage Applet to run in Netscape or IE, the solution is to install Java Plugin in Netscape or IE, you can use the JDK-implemented signature applet can be in these two The browser is running. Q: Use JNI technology can call the C subscription from the Java application, but how to make the C library can call another C subscription? A: If a C library C1 called by Java is still needed 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, and compile .javac Java file name to generate C program header file javah -jni The Java file name (without suffix .java) writes the C program C1.c called by Java, and C2.c called C1, and compiled .cc -g -iinclude path name c2.c -o libc2. SoCC -G -Iinclude path name -lc2 c1.c -o libc1.so Setting Environment Variable Stenv LD_Library_Path Libc1.so, libc2.so location path: $ {ld_library_path} Run Java App Quality: How to list the PC file system in Java language All drive names? A: In Java 2, the FILE class in the java.io package adds method Listroots () to achieve this. Q: Why does Runtime.exec ("ls") does not output? A: Call runtime.exe The C method will generate a local process and return an instance of a process subclass that can be used to control the process or obtain the process. Due to the child process created by the runtime.exec method, there is no end or console. Therefore, the standard IO of the child process is redirected by process.getoutputStream (), process.getinputstream (), process.GeTITERRORSTREAM () method is redirected to its parent process. Users need to use these streams Enter data or acquire the output of the sub-process to the child process. So correct the runtime.exec ("ls") 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 ());} Q: How to generate signage applets 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 signatures. JAR file, detail, please refer to: http://java.sun.com/security/usingjavakey.html, Java 2 has made a relatively large improvement on the signature mechanism, allowing users to set security permissions 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 generating a simple signature applet is as follows: // Generate a key, the key is not named Joe, password For SIGN12, stored in keytool -genkey -alias joe -keypass signal in the keystore // to package SIGNEDAPPLET.CLASS and related files into JAR file JAR CVF SIGNEDAPPLETDEMO.JAR / / The self-signed certificate generated by KeyTool Generate a signature applet (JAR file) jarsigner -keystore joesteore -signedjar Joe.jar Signedappletdemo.jar JoE // Out the self-signed certificate from the keystore to the file keytore-ketport -keystore joesteore -alias joe -file joe.cer, for the signature applet The acceptor Susan needs to securely perform the signature applet: // get Joe's certificate: // to get Joe's certificate and read it into the keystore in the keystore in the keystore. SusanStore // Run PolicyTool Generate Policy file policytool // run with AppletViewer, or install Java Plugin in your browser. For the signature Applet in Java Plugin, please refer to the following page: http: // j Ava.sun.com/security/signexample12/ Note: The above example is simplicity, using the self-signed certificate generated by KeyTool. In fact, users can also apply for electronic certificates to the commercial CA center using KeyTool-CautReq. Q: If you pass ObjectOutputStream Write Object multiple times in a file, why use ObjectInputStream when reading these objects? A: When the default Serialize is implemented, an ObjectOutputStream constructor and an ObjectInputStream constructor must correspond one. The constructor of the ObjectOutputStream is written to the output stream, while ObjectInputStream first reads this identity head. Therefore, when writing to Object in a file multiple times, this file will contain multiple identification heads. so when used to deserialize the ObjectOutputStream ObjectInputStream, StreamCorruptedException generated. one solution is a class constructor ObjectOutputStream and covering the writeStreamHeader () method. the writeStreamHeader after being covered () method should be determined whether the file for the first time Write Object, carbonyl? Call super.writestreamhead ();

If you write Object when you add an additional manner, you should call the ObjectOutputStream.Reset () method. Q: The Serialization class is a flow-oriented, how should you write objects to a random access file? A: Currently, there is no direct method to write objects into random access files. But you can use the ByteArray input / output stream as an intermediary to read or read or read the word from the random access file. Section, and you can use byte stream to create object input / output streams for reading and writing. Need not to note that in the byte stream, you want to include a complete object, otherwise an error will occur when reading and writing objects. For example, Java.io.byteArrayOutputStream can be used to get the byte stream of ObjectOutputStream, which can be obtained from the BYTE array and write it into a random access file. Instead, we can read the byte array from the random access file, using it ByTearRayinputStream can be constructed to read ObjectInputStream to read objects. Q: When running RMI applications, you can not manually start the name service RMIRGISTRY, but start from the program? A: Yes. Java.rmi package provides classes Java.rmi.Registry.locateREGISTRY, is used to get a 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 RMIREGISTRY. In addition, LocateRegistry.getRegistry (String Host, INT port) method can be used to obtain a name service. Q: How should I set the printing attribute of the printer name when using the class printjob? A: Use the following method to get PrintJob instance to control the print operation: Toolkit .GetPrintJob (Frame F, String Jobtitle, Properties Pro) So settings for printing properties can be implemented by setting Prop properties, printing properties include: aff.print.destination: can be "printer" or "file" AWT.Print .printer: Printer Name AWT.PRINT.FileName: Print file name AWT.PRINT.NUMCOPIES: print account AWT.PRINT.OP TIONS: Print Options for Print Commands AWT.PRINT.ORIATATION: Print Direction, can be "portrait" or "landscape" aff.print.papersize: Paper size, can be "letter", "legal", "executive" or "A4 "

Q: The thread class in JDK1.1 defines the suspend () and resume () method, but it is already in JDK1.2, what method should be used to replace it? A: thread.suspend itself is easy to generate dead locks. If one The target thread is locked for a key system resource, then the thread is SUSPEND, so that other threads will not be able to access the system resource unless the thread is resume, if another thread will call the resume, make the thread continue Operation, and before this, it also needs to access this system resource, will result in a deadlock. Therefore, in Java 2, a popular way is to define the status variable of the thread and poll the target thread. When the status is a suspension state, you can use the wait () method to wait in the waiting state. Once the thread is required to continue running, the other thread calls the notify () method to inform it. Q: Use JDBC programming, how to control the result set Resultset The pointer makes it possible to move up and down, and move to the first row of the result set and the last row? A: In JDK1.1, only the next () method only defines the next () method supports the downward of the data pointer. But in Java 2, the ResultSet class adds the following method to support the movement of the data pointer, including: resultSet.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 methods. Currently, INTERSOLV and OPENLINK are available in JDBC driver manufacturers with products. Support JDBC 2.0. Q: Which Web Server supports servlet? How to make IIS support servlet? A: Currently, server-side products that support servlet are: Sun Java Web Server, Lotus Domino Web Server, BEA Weblogic TenGah Server, Jigsaw, Netforge, Acmeserver, and Mot Bay'sJetty. 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 /) Wait. Q: How to store images into image files in Java applications? A: Java Advanced Imaging API (included in Java Media API) Allows complex, high-performance image processing in Java applications The .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 stored on the BMP file: OutputStream OS = New FileOutputStream (fileToWriteTo); BMPEncodeParam param = new BMPEncodeParam (); ImageEncoder enc = ImageCodec.createImageEncoder ( "BMP", os, param); enc.encode (img); os.close (); programming guidelines for storing image files, Refer to the following page: http://java.sun.com/products/java-media/jai/fordevelopers/jai-guide/ Q: How to use the Java language to read and write data to serial port? Font> A: Sun's Java Communication API2 .0 can be used to read the serial port, which supports the RS232 serial port and IEEE 1284 and provides a string / parallel communication mechanism that is not related to the platform. Detailed documentation, please visit: http://java.sun.com/products/javacomm /

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

New Post(0)