Java FAQ Highlights (from Sun China Official Station)

xiaoxiao2021-03-11  186

Q: How do I set up the environment variable of Java 2 (JDK1.2)? A: 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 the system Class library and user's current path. Setting of Java 2 Environment variables As shown in the following example: Solaris Platform: SetENV Java_Home Java2 installation path STENV PATH $ java_home / bin: $ {pat} Windows platform: set java_home = java2 installation path set PATH = $ java_homebin;% PATH% 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. Q: Q: Q: Q: Q: Q: If an error occurs when running a 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 are jdk The level of support is also different. Therefore, running Java Applet in the Netscape or IE browser, it is recommended to use the Tool AppletViewer or Sun's Hotjava browser provided by JDK to test the applet to determine the occurrence of errors. The browser is related. 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 Java Plugin using the Hotjava browser or installing Sun. If the applet runs in the HotJava browser or AppletViewer, you should check the Applet program based on the error prompt. Q: When using JDBC to insert data into the database or extract data from the database, sometimes the Chinese characters will be displayed as garbled? A: This problem is usually related to the implementation of each JDBC Driver. At present, most JDBC Driver uses local encoding format to transmit Chinese characters, such as Chinese characters "0x4175" will be transferred to "0x41" and "0x75". Therefore We need to convert characters returned by JDBC Driver and to send characters to JDBC Driver. When used When JDBC Driver is inserted into the database, you need to transfer Unicode to Native Code; when JDBC Driver 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.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 If the JDBC Driver Manager sets the correct 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 you can display properly? A: javax.servlet.http.httpResponse class is used to generate return pages. Methods defined by httpResponse GetputStream () can get instances of servletOutputStream, so users can take servletoutputstream The .write method writes the contents of the return page in the output stream. But servletOutputStream uses the default encoding method. If you want to make the Chinese characters in the return page, it is best to specify the character encoding used. configuration typically requires 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 the test"); OW.Flush (); OW.Close ();} 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 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, when the Java Webserver starts, the class content is automatically added. To the ClassPath environment variable. Modify the httpd.nojre file, add the path name where the user class file is added to the ClassPath environment variable. Q: Why is used on a Windows platform? Naming.lookup is slower when getting a remote RMI object? A: The machine's network settings are incorrectly probably caused by this problem. RMI uses Java network classes, especially Java.Net.ineTdress classes, which will query TCP / IP hostname, including the IP address to the host name mapping and host named IP address. In the Windows platform, this query function is implemented by the local Windows Socket library. So delay is in Windows library Medium, not RMI. If your machine is set to use DNS, the problem is usually the DNS server can't find the host name, and the delay you find is the delay of the DNS query. Please try all the RMI communications involved all The hostname / IP address is added to the local file WinntSystem32DriverseetStChosts or WindowsHosts. The format is as follows: IP address hostname should significantly reduce the time spending the query. Q: How to set up the information when writing Java Application, in order to access the outside Site? A: If you access the external website in Java Application, you should first set up 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; connection = (httpurlconnection) u.openconnection (); ..... Q: Swing component jlist's list data modified, how to inform JList change display? A: The JList component has a separate display mode ListModel to represent Jlist's display data. After Jlist creation, the value of the JList data element and the number of data elements can be dynamically changed. Jlist Observes the changes in data in its data mode ListModel. So, therefore, The correct implementation of a ListModel should notify the event's listener when each data is changed. When using the constructor jlist (Object []), the system will automatically create an instance of a defaultListModel to store Jlist's display. Data, you can call the simply method defined in DEFAULTListModel to dynamically modify the JList's data, such as RemoveEleMentat (INDEX), AdDelement (Object), etc. DEFAULTLISTMODEL will notify Jlist to change the data on data while modifying the data. Q: In Java Applet How to implement a pattern 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 creating a dialog. Because applet is a subclass of the Panel class, no Can be used as a parent window of the dialog, so we must first get the window in which 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 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, compile. Javac Java file name generating 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.so cc - G-INCLUDE 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 Q: How to list PC files in Java language All drive names in the system A: In Java 2, the File class in the java.io package adds a new method LISTROOTS () To achieve this. Q: Why does 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 obtain information about the process. Since the child process created by calling the runtime.exec method does not have its own terminal or console, the standard IO of the child process is process.getoutputStream (), Process .getinputStream (), process.GeterrorStream () method redirects to its parent process. Users need to use these stream to enter data or get the output of the child process to the child process. So correctly execute Runtime.exec ("ls") routine 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 a signature applet so that the applet can access local resources? A: In JDK1.1, you can use the javakey command to generate public key, private key, certificate and signature JAR file, please refer to: http: //java.sun.com/security/usingjavakey.html and Java 2 have 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 are implemented 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, the password is SIGN12, stored in the keystore Joestore KeyTool -Genkey -Alaias Joe -KeyPass Sign12 -keyStore Joestore // Package SignedApplet.class and related files into JAR file JAR CVF SIGNEDAPPLETDEMO.JAR // Generate self-signed certificate generated by KeyTool to generate a signature applet (JAR file) Jarsigner -KeyStore Joestore -SignedJar Joe.jar Signedappletdemo.jar Joe // Output Self-signed Certificate from KeyStore to file keytore-ketport-ready, joesteore -alias joe -file joe. Safely perform Joe written signature applet: // get JoE certificate and read it into the keytore in the keystore in the keystore, the keytore-IMPORT -ALIAS JOE-FILE JOE.CER -KEYSTORE SUSANSTORE / / Run PolicyTool to meet the Susan requirements Policy file policy // runs with AppletViewer or runs Java Plugin in your browser. 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 simple Same, use the self-signed certificate generated by KeyTool. In fact, users can also apply for an electronic certificate to the commercial CA center using KeyTool-Cautreq. Q: If the ObjectOutputStream is written to an additional manner multiple times in a file, why use ObjectInputStream read these take will produce object StreamCorruptedException a:? implemented using the default serializetion time, a configuration and a configuration ObjectOutputStream ObjectInputStream must correspond .ObjectOutputStream constructor writes an identification header to the output stream, and ObjectInputStream This logo will first be read. Therefore, when writing Object in an additional manner multiple times, the file will contain multiple identity heads. So use ObjectInputStream to deSerialize this ObjectOutputStream, streamcorruptedException will be generated. The method is to construct a subclass of ObjectOutputStream and override the WriteStreamHeader () method. The written WriteStreamHeader () method should determine if it is written to the Object in the file, and carbonarbonal is called Super.WritestReamHeader ();

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 "

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

New Post(0)