Java FAQ Gallery

Source: Internet
Author: User
Tags file system header html page iis netscape web server first row thread thread class
Problem

Sys.put ("ProxyHost", "myHTTP.proxyserver.com");

Sys.put ("ProxyPort", "80");

System.setproperties (SYS);

u = new URL (website);

Connect = (httpurlconnection) u.openconnection ();

.....

Q: The Swing component JList list data has been modified, how to notify the JList change display?

For:
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.

Ask:
How do I implement a modal dialog box in Java applets?

For:
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?

For:
The Appletcontext, appletcontext.showdocument (URL) associated with the applet can be obtained by the Java.applet.Applet.getAppletContext () method. method to display another Web page in the browser that the applet is in.

Ask:
Can a signed applet, implemented with JDK, run in Netscape or IE?

For:
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.

Ask:
JNI technology allows you to invoke the C program library from Java applications, but how do you make the C program library call another C library?

For:
If a Java-invoked C-Library C1 still needs to invoke another C-Library C2, you should join the library C2 when compiling C1, as follows (Solaris platform):
Write the Java file that calls the C library and compile it.
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 path name-LC2 c1.c-o libc1.so

Setting environment variables
setenv Ld_library_path libc1.so,libc2.so Path
:

Running Java applications

Ask:
In the Java language, how do I list all the drive names in the PC file system?

For:
In the Java 2 version, the file class in the Java.io package adds a new method Listroots () to implement this functionality.

Ask:
Why is runtime.exec ("LS") without any output?

For:
Calling 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:

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 ());

}

Ask:
How do I generate a signed applet to enable the applet to access local resources?

For:
In jdk1.1, you can use the Javakey command to generate the public key, private key, certificate, and signature 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

Keytool-export-keystore Joestore-alias Joe-file Joe.cer

For the recipient of the signed applet, Susan, you need to perform the following steps safely

Signed applet written by Joe:

Get Joe's certificate and read it into the KeyStore Susanstore

Keytool-import-alias joe-file Joe.cer-keystore Susanstore

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.

Ask:
If you write object more than once in a file by ObjectOutputStream, why do you have streamcorruptedexception when you read the object with ObjectInputStream?

For:
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.

Ask:
The serialized (serialization) class of an object is stream oriented, how should the object be written to a random access file?

For:
Currently, 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.

Ask:
When running RMI application, can you start the name service rmiregistry instead of manually, but from the program?

For:
OK. 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.

Ask:
How do I set print properties such as printer names when using class PrintJob for print operations?

For:
Use the following method to obtain an instance of PrintJob to control the print operation:

Toolkit.getprintjob (Frame F, String JobTitle, Properties prop)

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"

Ask:
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?

For:
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.

Ask:
Using JDBC programming, how should 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?

For:
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.

Ask:
What kinds of Web servers support the servlet? How do I make IIS support the servlet?

For:
Currently, the server-side products that support the servlet include: Sun's Java webserver,lotus dominogo webserver,bea WebLogic Tengah Server,jigsaw,netforge, Acmeserver 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.

Ask:
How do I store images in an image file in a Java application?

For:
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 ();

Imageencoder enc = imagecodec.createimageencoder ("BMP", OS, param);

Enc.encode (IMG);

Os.close ();

For a programming guide for storing image files, refer to the following pages:

http://java.sun.com/products/java-m...pers/jai-guide/

Ask:
How do I read and write data to a serial port in the Java language? Font>

For:
Sun's Java communication API2.0 can be used to read and write the serial port, which supports the RS232 serial port and the IEEE 1284 interface, providing a platform-independent string/port communication mechanism.




Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.