Java Common Questions Collection 25 Q:

xiaoxiao2021-03-06  73

Java FAQ 25 Q: 1. Q: How to set up the environment variable of Java 2 (JDK1.2)? A: Java 2 After installation, you need to set the path and java_home environment variables. Unlike JDK1.1: Set good Java_home After the 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: SetENV Java_Home Java2 installation path setenv path $ java_home / bin: $ {pathing} 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 supports Java 2.3, Q: If you have an error when running a Java applet in the Netscape or IE browser, how to determine an error range? A: When the Java Applet is running in the browser, use browsing The default JVM itself. Different browsers have different supports 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 Browse The device to test the applet to determine the error of 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 time, the solution can be It is a Java Plugin using the Hotjava browser or install Sun. If the applet runs in the Hotjava browser or AppletViewer, you should check the Applet program based on the error prompt. 4, Q: When using JDBC to insert data from the database or from When extracting data in the database, why sometimes the Chinese characters will be garbled? A: This problem 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 transferred to "0x41" and "0x75" to transmit. 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 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, 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 (), Process.GeterrorStream (), Process.GetrRRRREAM () 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 have a relatively large improvement on the signature mechanism, allowing users to set security more flexibly. Java 2 provides three tools: KeyTool, PolicyTool and Jarsigner To implement the signature applet. For example, Joe has written a signature app: Signedapplet.java, then generate a simple signature applet process as follows: // Generate a key, the key is not named Joe, the password is Sign12, stored in the keystore KEYTOOL -GENKEY -AAS JOETOL -GENKEY -AAS JOE -KEPASS SIGN12 -AAS JOE -KEYPASS SIGN 12-Alias ​​JoeStore // Package SignedApplet.class and related files into JAR file JAR CVF SIGNEDAPPLETDEMO.JAR / / The self-signed certificate generated by KeyTool generates a signature applet (JAR file) Jarsigner -KeyStore Joestore -SignedJar Joe.jar SignedappletDemo.jar Joe // Outputs the self-signed certificate from the keystore to the file keytore-ketport -keystore joesteore -alias joe -file joe.cer, the acceptor Susan for the signature applet, you need to pass the following Steps to securely perform the signature applet: // get Joe's 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 Susan The required Policy file policytool // runs with AppletViewer, or installs Java Plugin in the 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, using the self-signature generated by KeyTool Certificate. In fact, users can also apply for electronic certificates to the commercial CA center using KeyTool -Certreq. 17, Q: If the ObjectOutputStream is written to Object multiple times in a file, why use ObjectInputStream to read these Object When streamcorruptedException A: When using the default serialize, a configuration of an ObjectOutputStream and an ObjectInputStream constructor must correspond one by one. The constructor of ObjectOutputStream is written to the output stream, and ObjectInputStream will first read this marker head. Therefore, when writing Object in a file multiple times, the file will contain multiple identity heads. So use ObjectInputStream to deserialize this ObjectOutstReam, a solution is to construct an ObjectOutputStream. Subclasses, and override the WriteStreamHeader () method. After the covered WriteStreamHeader () method should determine if it is written to Object in the file, carbonyl?

If not, when writing Object in an additional manner, the objectOutputStream.Reset () method should be called. 18. Q: The Serialization class is a flow-oriented, how to write objects to random access files ? A: Currently, there is no direct way to write objects in a random access file. But you can use the ByteArray input / output stream as an intermediary to read or read or read from the random access file. Bytes, and you can use byte flow 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. 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 a random access file. Instead, we can read the byte array from the random access file. Using it can construct ByTearRayinputStream, it can be constructed to read objects. 19, ask: When running RMI applications, you can not start the name service RMIREGISTRY, but start from the program? A: Yes. Java.rmi package The class java.rmi.registry.locateREGISTRY.LOCATEREGISTRY is provided to 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 RMIREGISTRY. In addition , LocateRegistry.getRegistry (String Host, int port) method can be used to get the name service. 20, ask: How should I set the printed attribute of the printer name using class printjob? A: Use the following method to get the instance of PrintJob The printing operation: Toolkit.GetPrintJob (Frame F, String Jobtitle, Properties Pro) So settings for printing properties can be implemented by setting the properties of the Prop, including: aff.print.destination: can be "printer" or "file" aff.print.printer: printer name AWT.PRINT.FILENAME: Print file name AWT.PRINT.NUMCOPIES: print account AWT.PRINT.Options: Print Command Print Options AWT.PRINT.ORIETATION: Print Direction, can be "portrait" or "landscape" aff.print.papersize: Paper size, can be "letter", "legal", "executive" or "a4"

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

New Post(0)