Some Java applications collected online

xiaoxiao2021-03-06  75

Let me talk about more cool ways to get the appearance of the program in JBuilder!

Java program default appearance (Lookandfeel) can be changed to Java appearance, MotiF appearance, Windows appearance, Mac appearance;

And the appearance of Java has five styles are sea blue gemstone, grandmother green style, ruby ​​style, charcoal style,

High contrast style.

The specific method of appearance changes is as follows:

1: You can call one of the following three in the program directly:

Import javax.swing. *;

UIManager.SetLookAndfeel ("com.sun.java.swing.plaf.motif.motiflookandfeel");

UIManager.SetLookandFeel ("javax.swing.plaf.metal.MetallookAndfeel");

UIManager.SetLookAndfeel ("com.sun.java.swing.plaf.windows.windowslookandfeel");

2: Or use the menu to transform:

Import javax.swing. *;

JMenuBar MB = new jmenubar ();

JMenu File = New Jmenu ("Look & Feel", True;

ButtonGroup Buttongroup = New Buttongroup ();

Final uimanager.lookandfeelinfo [] info = uimanager.getinstalledLookandFeels ();

For (int i = 0; i

JRADIOBUTTONMENUITEM ITEM = New

JRADIOBUTTONMENUITEM (INFO [i] .Getname (), i == 0);

Final string classname = info [i] .getclassname ();

Item.addActionListener (New ActionListener () {

Public Void ActionPerformed (ActionEvent AE) {

Try {uimanager.setlookandfeel (classname);

Catch (Exception E) {system.out.println (e);

Swingutilities.UpdateComponentTreeui (Touchyfeely.this);

});

Buttongroup.Add (item);

File.Add (item);

}

Mb.add (file);

Setjmenubar (MB);

}

By the previous published, a big rich friend, please change the content to JBuilder related content. Thank you.

I hope to write a lot of essence, don't bill it!

From:

Humanc2d4,

Time: 2003-5-16 14:45:00,

ID: 1867298

Let me talk about the digital signature of the applet in jbuilder (reproduced from: Programmates)

Since Java technology has started applying, people have given great attention to the security issues of Java platforms and security issues caused by deploying Java technology. Especially after JAVA2 released in November 1998, Java's security architecture has undergone fundamental improvements. For end users, it protects files and private data from malicious programs or viral infections and destruction, identification code providers. identity of. For developers, by using an API method, security features can be integrated into applications, because the architecture of the API can define and integrate the use of specific resources, encryption, security management, policy management, and provide Some classes to manage public key certificates for public key / key pairs and trusted user groups. At the same time, system administrators, developers, and users can use the tool management key library it provides, generate digital signatures in the JAR file, the signature integrity detection, creation, and modify the policy file. According to the Java designer's point of view, Java security includes two aspects of content, first provide Java as a safe platform to users, on which the Java program can be safely running; secondly provides security with Java programming language Tools and services, which makes some areas of security and very sensitive areas such as the enterprise world can also apply Java technology. This article will introduce the security new features of Java2 and the specific implementation methods of the Applet digital signature under this new feature. Java2 adopts a new security architecture as shown in Figure 1, and provides a lot of new specials based on this security architecture?

1.1 Idiobi Access Control

This ability exists in JDK from the beginning. But use it, the writer of the application has to do a large number of programming work, for example, create subclasses of the SecurityManager and the ClassLoader class and make it userize. HotJava1.0 is a such application that allows the browser user to choose from several different security levels. However, this programming involves very sensitive security issues, which requires programmers to have a deep understanding and sake of software security. The new security architecture will make these simple and safe.

1.2 Easy to configure security policies

Similar to the above, this ability exists in the original JDK, but not in use, and writing security code is not a simple thing. Thus, it is expected that the application's writers and users can set the security policy without programming.

1.3 Easy to expand access control structure

Up to JDK1.1, in order to create 1 new access license, you must add 1 new Check method in the SecurityManager class. The new security architecture allows you to set various types of access licenses (each representation of 1 system resource) and automatically processes all correct access licenses (including undefined licenses).

1.4 Safety check to extend to all Java programs

All local code is a trusted built-in concept will not exist. Instead, it will be a local code (such as non-system code, mounted in a local application package, etc.) obey the same security control as Applet, but can declare The policy of local code is tolerate, so that these codes can be considered to be fully credible and efficiently run. The above principles can also be applied to the signed applet and any Java application.

2 Java2 security system concept and operation mechanism

2.1 protection domain

A basic concept in the Java2 security architecture is Protected Domain. One domain can be divided by an object set, which can be directly accessed by one subject. The body is an entity that is granted permitted in a computer system. The sandbox for JDK1.0 is a protected domain example with a fixed boundary. The concept of protecting domains is a convenient mechanism that plays a packet and isolation between the protection unit. For example, we can separate the protected domain to avoid direct interactions between them, so that any allowed interaction must be explicitly allowed by trusted system code or related domains. The protection domain is usually divided into a clear 2 category, system domain, and application domain. All protected external resources such as file systems, network facilities, and screens and keyboards can only be accessed through the system domain. Figure 2 shows the composition of the domain of one Java application environment. Conceptually, one field includes 1 group class, which is granted the same set of licenses. The protection domain is determined by the current policy. The Java application environment maintains mapping from code (classes and instances) to their protection domains and then to their licensed, as shown in Figure 3. One thread execution may occur completely in one single protection domain, or it may also involve one application domain or a system domain. For example: an application for 1 print message will have to interact with the system domain because the system domain is the only access point for the output stream. At any time in this case, both the application domain cannot obtain any additional licenses except the print message by calling the system domain, otherwise it will be a serious security hidden danger. In the opposite case, one system domain calls 1 method from one application domain, such as when 1 APT system domain calls 1 Applet's painting method to display this applet, valid access and application domain Allowed current permissions are the same at any time, and this is also essential. In other words, a domain with lower privileges cannot obtain additional licenses by calling a domain of higher privileges or by a higher permissions. The above related 1 thread involves two protected domains naturally summarizes a thread that traverses multiple protected domains, and a simple and cautious experience of calculating licensing is:

(1) A license set that performs thread can be considered a integration of all protected domains traversed by the thread.

(2) When 1 code calls the DOPRIVILEGED method, the permission to perform threads is considered to be a protected domain that includes all code and a protective domain that is directly or indirectly called. That is, one trusted code can be temporarily accessed through the DOPRIVILEGED method, which is necessary in some cases. For example, one application may not be allowed to directly access files containing fonts, but the system utility that displays text must obtain those fonts on behalf of users.

During execution, when requesting access to 1 critical system resource (such as file I / O and network I / O) or API method requires 1 sensitive operation, such as reading 1 file, resource processing code is directly or indirectly called 1 Special method called AccessController class, the access control class makes the decision to give the request or operation occurred by checking the call stack. In the call stack is a member method of some classes that need to be called, because each class belongs to some protected domains, and each protected domain has established some policies, so each method of the calling stack is assigned 1 Group permissions. The access control class begins with the top, check each method from the top, see if the method is allowed by the protected domain, if a method permission is found, not allowed, access control

It is throwing safety unusual; There is a special case, that is, when the access control traverses calls the stack, it will look for the privileged domain. If there is an excellent domain, even if there is no reach the bottom of the stack, the access control will stop traverse the callout stack and allow the operation. . Although new security

The mechanism seems to have added a number of calls to the API method, but Java2 does use some technologies to accelerate

The process of checking permissions, such as access control, will filter out repeated domains and stop checking when encountering the first priority domain.

Note The additional operation will be a local method call, and the SUN's reference test shows a new security check is quite fast.

Finally, each domain includes a system or application domain that can add internal resources in its domain boundaries. For example, a bank system application may need to support and protect some of its inside, such as checking, save

And withdrawals, etc. Since this protector is unlike those predictable semantics can be preset by JDK, thus this

The protection is best to keep it to the system or application developer.

At present, one domain is individually identified by a code source (CODESource), which encapsulates two features of the code running in this domain: code base address and public key certificate set, the public key corresponds to the domain A private key for all code signed. Thus, classes from the same key and from the same URL are placed in the same domain. One domain is also included in this domain license to grant code, which is determined by the current security policy.

2.2 Certificates, Keyware and related tools

Under the Java2 security system, one applet development and running process is as follows:

In the distribution terminal of the code:

(1) Develop Java source procedures and compile them.

(2) Package class files and resource files with JAR tools.

(3) Create a public key and key with KeyTool, generate X. 509V1 signing certificate, output certificate.

(4) Digital signature of the JAR file with the generated key via the JARSIGNER tool.

At the receiving end of the code:

(1) Enter the certificate with the keytool as trusted.

(2) Create and modify security policy profiles and access access to the security policy configuration file with PolicyTool.

(3) From the network, the field code is obtained, verify the digital signing certificate and the integrity of the digital signature certificate and the integrity of the document code.

(4) Verify the legality of the bytecode, allocate the appropriate permissions according to the policy file.

(5) Execute the code, and recover the memory by the garbage collector after completion.

Before using the public key to verify the digital signing certificate, the recipient needs to confirm the reliability of the public key itself, so it is usually provided to provide a certificate containing the public key rather than the public key itself. 1 certificates include:

(1) 1 public key.

(2) 1 unique name entity (individual or company), it is owner of the certificate, including user name, company, organization, city, address, national code, provincial, etc.

(3) Digital signature: 1 certificate is signed by 1 distributor's entity, guaranteed that the certificate does contain another

The public key of the entity (owner).

(4) Identifier information of the distributor.

For the recipient to verify his digital signature with the distributor's public key to check the legality of the certificate. However, the public key may be included in another certificate, and the digital signature needs to be verified with the public key of the distributor of another certificate, so nested until a public key is confirmed by the recipient. If the recipient cannot establish a trust chain, for example: 1 distributor's certificate is not legal, you can calculate the fingerprint with the keytool-import command, each fingerprint is a related short number, which is uniquely reliable to identify the certificate (a fingerprint is a The hash value of certificate information calculated by the information summary algorithm), the recipient can call the owner of the certificate and compare the issued certificate and the fingerprint of the reception certificate, if the fingerprint is the same, the certificate is different. Therefore, it is possible to ensure that the certificate is not modified during transmission. Another potential problem is the identity of the sender's identity, sometimes a certificate is self-signed, that is, the key is signed with the key corresponding to the public key in the certificate, if the recipient already knows or trust the sender, then there is no problem. . Otherwise, the sender needs to obtain a certificate from a trusted third party. This third party is usually a certificate of authorization agency CA, then send a self-signed certificate signing request CSR to CA, by the CA verification CSR signature and send CSR identity, license, and other information. The CA then the certificate of signing with the CA, authorizes the CSR's sender as the owner of the public key, and anyone can use it to verify the signature of the certificate, in many cases CA itself There is a certificate from a higher level of CA to constitute a certificate chain. All trusted certificate entities can be introduced into a key bar as a trust certificate, and the public keys in each certificate can be used to verify the signature generated with the corresponding key. The sender also provides a public key certificate corresponding to the signed key when sending a signature code and a document. With the keytool-export command or the API function, you can output a certificate into the file from the key library, and then send this file to the required recipient, and introduce it into the keystore by the recipient with the KeyTool-Import command or API function. If you use the Jarsigner tool to generate a signature for the JAR file, he will remove the certificate and certificate chain from the key library, and put it together with the signature in JAR files.

The key and the corresponding public key certificate are placed in a database protected by the password, called a keystore. 1 key library contains two types of entries, trusted certificates entry, key and certificate entry, each contains 1 key and the key certificate corresponding to the key, and each entry in the key library has 1 individual name is identified. The owner of the 1 key library can have multiple keys in the key library, which can be accessed by different alias, each alias is usually named by a specific role of the key used by the owner of the key, and the alias can also be identified the key. the goal of. E.g:

SignPersonalemail can be used to identify an entry for 1 key library, and its key is used to sign an individual email, Signjarfiles is used to identify one entry, and its key is used for signature JAR files.

3 Applet's digital signature authentication implementation specific method, step

3.1 Combined with my own Java2-based applet

My project is to use Applet to make a real-time message queue monitor. Since local resources are involved, digital signatures and certifications must be performed on Applet. The environment I use is Windows2000, the application server is WebLogic 6.0, the development environment is JBuilder 4.0. I remind everyone to pay attention to the concept of the server and the client. Those files should be on the server, those files should be on the client.

First, use JRE 1.3.0_01 (Java Run Environment 1.3.0.1 version) to replace the JVM (Java virtual machine) of IE,

Www.java.sun.com go to download, download well, first installed on the client, the installation process is very simple. In the HTML file of the server-side call applet, it also need to include it in order to download the client download, the specific way of writing, please look down;

Specific steps are as follows:

Service-Terminal:

1. All package files need to be used in all package files (I have to use the weblogic JMS package to use the command jar xf weblogicc.jar), then use the JDK package command to compile the monitor. Class and the package just unzipped Pack into a package together. (Premise that I have placed the monitor and unlocked bags in the same directory), all the commands under the DOS state, see the bin directory of JDK1.3 (1.2), the command is as follows:

Jar CVF Monitor.jar * .class

This command generates a package called Monitor.jar

2. Create KeyStore and Keys for the package file created (Monitor.jar). The KeyStore will be used to store the private keys and public key certifications, and Alias ​​alias is taken here for Monitor.

The command is as follows:

KeyTool -Genkey-Keystore Monitor.Keystore -Alaias Monitor

This command generates a keystore file called Monitor.KeyStore, then this command, the system will ask you a lot of questions, such as your company name, your address, you have the password you want to set, etc., all by your casual write.

3. Sign by using the key you just generated to sign the JAR file

The command is as follows:

Jarsigner -keystore Monitor.KeyStore Monitor.jar Monitor

This command will sign the Monitor.jar file without generating a new file.

4. Import the public key into a CER file, this CER file is the only file to copy to the client.

.

The command is as follows:

Keytool -Export-Keystore Monitor.Keystore -Alaias Monitor -file

Monitor.cer

This command will generate a Monitor.cer authentication file, of course, these steps may ask you the password you just set.

This completes the server side settings. At this time, you can copy the JAR file and the keystore file and the CER file (I am Monitor.jar, Monitor.KeyStore, Monitor.cer), I am using WebLogic6.0, so copy it to C: EAWLSERVER6.0CONFIGMYDOMAINAPPLICATIONSDEFAULTWEBAPP_MYSERVER is under a directory under its own.

Client:

1. First, JRE 1.3.0_01 should be installed, and then copy the server-side Monitor.cer file to JRE's specific directory, I am here:

C: Program filesjavasoftjre1.3.0_01libsecurity directory.

2. Pour the public key into JRE CACERTS (this is the default keystore of JRE)

The command is as follows:

KeyTool -Import -Alaias Monitor -file Monitor.cer

-Keystore Cacerts

Note that this is to enter the password of the cacerts, it should be Changeit, not your own keystore's password.

3. Modify the Policy policy file, use the command policytool system in the DOS state, will automatically pop up a policytool dialog, as shown in Figure 4, first select the Open item of the File menu, open C: Program

Filesjavasoftjre1.3.0_01libsecurity directory Java.Poliy file,

After selecting Change KeyStore in the EDIT menu, in the dialog box, enter file: / c: / program files /javasoft/jre/1.3.0_01/lib/security/cacerts, here should pay attention to the backslash, Enter JKS in New KeyStore Type, which is a fixed format of Cacerts, and then click Add Policyntry to enter CodeBase in the dialog that appears:

http: // URL: 7001 / *

The URL is the server's IP address, 7001 is my weblogic port, if you are in other application servers, such as Apache, that port number can be omitted. Enter (alias alias) in SignedBY: This is Monitor and click the Add Peimission button. In the PERMISSION, in the dialog that appears, select the permissions you want to give this applet, this is a lot of permissions, readers can find information to find themselves. I am using allpeimission, enter alias in the right signedby: Monitor is finally saved, in the File menu SAVE item. Of course, you can see that I have implemented signature authentication for multiple packages.

This is completed so that the settings of the client. When the client is running the applet program with IE, you will ask if you authorize the signature, select Authorization, the package will automatically download from the server to the local computer, and IE will automatically start JRE, and you can see it in the lower right column. The Java console equivalent to IE.

4. Call an applet's HTML file

Everyone knows that the HTML file for the normal call of Applet is no longer used by Java2 security, and it is changed to the ActiveX type call. Specific points in IE and Nescape Different Writings, this can find ready-made tutorials on Sun online. I don't have much to say, just give everyone the HTML written by IE.

Message Center Real-Time Monitoring Platform


Width = "900" height = "520" align = "baseline"

Codebase = "http://192.168.2.217:7001/j2RE-1_3_0_01-win-i.exe#version=1, 3, 0, 0">

Among them, I want to emphasize, because Applets need to be re-packaged every change, the procedures are very cumbersome, so in the specific implementation, put some change parameters in the HTML file, pass it to the applet, this online There are a lot of articles, go see it yourself.

The other is that a friend asked me, then it is not too much trouble, every client has to perform a complex DOS command operation, I can only say that my level can only put a client file CER file And java.policy and cacerts files directly copy to the client, of course, this also has a defect, and if someone else's computer has authenticated, it will be lost. We can discuss these issues.

There is also a little optimization, just when packing, I only said that all the package and source creations that should be used to be used to hit a package. Thus, if the package is very large, it will affect the download speed, if you can use the local computer package, this JRE is also done, the specific to the JRE console to the control panel. Set. This will leave the reader to explore it.

From:

Humanc2d4,

Time: 2003-5-16 14:47:00,

ID: 1867304

I talked one of Java control Excel. (Borland.com)

Friends using the Windows operating system must not be unfamiliar with Excel, but to use Java language to manipulate the Excel file is not an easy task. Today, the Web is increasingly popular, the demand for the Excel file is increasing through the web, and the current more popular operation is to create a CSV (Comma Separated Values) file in the JSP or Servlet, and will file this file with MIME, TEXT / CSV type returns to the browser, then calls Excel and displays the CSV file. This is just to say that you can access the Excel file, but you can't really manipulate the Excel file. This article will give you a surprise, introduce you to an open source project ?? Java Excel API, use it, you can easily manipulate the Excel file.

Introduction to Java Excel API

Java Excel is an open source project, which can read the contents of the Excel file through its Java developers, create a new Excel file, update the existing Excel file. Using this API non-Windows operating system can also process the Excel data table by pure Java applications. Because it is written in Java, we can call the API to implement access to the Excel data table in a web application. The stable version released now is V2.0, providing the following features:

• Read data from the files such as Excel 95, 97, 2000;

• Read the Excel formula (you can read the formula after Excel 97); "Generate the Excel data table (format Excel 97);

Support font, numbers, date formatting;

Support the shadow operation of the cell, and color operation;

? Modify the existing data table;

• The following features are not supported, but will soon provide:

? You cannot read chart information;

You can read, but you can't generate formulas, any type of formula last calculated value can be read;

Application example

Read data sheet from an Excel file

The Java Excel API can either a file (.xls) of the local file system or from the input stream. The first step in reading the Excel data is to create Workbook (Terminology: Working). The following code snippet is explained how to operate: (full code see Excelreading.java)

Import java.io. *;

Import jxl. *;

... ...

Try

{

// Build a Workbook object, read-only Workbook object

/ / Create Workbook directly from local files

// Create Workbook from the input stream

InputStream IS = New FileInputStream (Sourcefile);

JXL.Workbook RWB = Workbook.getWorkbook (IS);

}

Catch (Exception E)

{

E.PrintStackTrace ();

}

Once you have created Workbook, we can access Excel Sheet by it. Refer to the following code segment:

/ / Get the first Sheet table

Sheet RS = rwb.getsheet (0);

We can access it through the name of Sheet, or you can access it by subscript. If you are accessible by the subscript, you should pay attention to the starting mark from 0, just like an array.

Once you get the Sheet, we can access Excel Cell (Terms: Cell). Refer to the following code segment:

/ / Get the value of the first line, the first column

Cell C00 = rs.getcell (0, 0);

String strc00 = c00.getContents ();

/ / Get the value of the first line, the second column

Cell C10 = rs.getcell (1, 0);

String strc10 = c10.getContents ();

/ / Get the value of the second line, the second column

Cell C11 = rs.getcell (1, 1);

String strc11 = c11.getContents ();

System.out.println ("Cell (0, 0)" "Value:" Strc00 "; TYPE:"

C00.Gettype ());

System.out.println ("Cell (1, 0)" "Value:" STRC10 "; TYPE:"

C10.gettype ());

System.out.println ("Cell (1, 1)" "Value:" STRC11 "; TYPE:"

C11.Gettype ());

If it is just a value of Cell, we can easily return any type of CELL value as a string by getContents () method. Cell (0, 0) in the sample code is text type, Cell (1, 0) is a digital type, Cell (1, 1) is a date type, through getContents (), three types of return values ​​are characters. If you need to know the exact type of Cell content, the API also provides a range of methods. Refer to the following code segment:

String strc00 = NULL;

Double STRC10 = 0.00;

Date strc11 = NULL;

Cell C00 = rs.getcell (0, 0);

Cell C10 = rs.getcell (1, 0);

Cell C11 = rs.getcell (1, 1);

IF (c00.gettype () == CellType.label)

{

Labelcell labelc00 = (labelcell) C00;

STRC00 = labelc00.getstring ();

}

IF (c10.gettype () == CellType.Number)

{

NMBERCELL NUMC10 = (Numbercell) C10;

STRC10 = Numc10.getValue ();

}

IF (c11.gettype () == CellType.date)

{

Datecell Datec11 = (Datecell) C11;

STRC11 = DATEC11.Getdate ();

}

System.out.println ("Cell (0, 0)" "Value:" Strc00 "; TYPE:"

C00.Gettype ());

System.out.println ("Cell (1, 0)" "Value:" STRC10 "; TYPE:"

C10.gettype ());

System.out.println ("Cell (1, 1)" "Value:" STRC11 "; TYPE:"

C11.Gettype ());

After obtaining the Cell object, the type of the cell can be obtained by getType () method, and then match the basic type provided by the API, forcibly converting into a corresponding type, and finally call the corresponding value method getxxx (), you can get Determine the value of the type. The API provides the following basic types, corresponding to the data format of Excel.

For details of each type, see Java Excel API Document.

When you complete the processing of Excel spreadsheet data, you must use the close () method to close the previously created object to release the memory space occupied by the read data table, which is especially important when reading a large amount of data. . Refer to the following code segment:

// When the operation is complete, turn off the object, release the occupied memory space

Rwb.close ();

The Java Excel API provides a number of ways to access the Excel data sheet, here I only briefly introduce several common methods, other methods, please refer to Java Excel API Document in the appendix.

? Methods provided by the Workbook class

Int getNumberofsheets ()

Number of worksheets in Workbook (Workbook), example: JXL.Workbook RWB = jxl.workbook.getworkbook (new file (sourcefile);

Int sheets = rwb.getnumberofsheets ();

2. Sheet [] getsheets ()

Returns an array of worksheets (Sheet) objects in Workbook, examples:

JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile);

Sheet [] sheets = rwb.getsheets ();

3. String getversion ()

Returns the version number of the API that is in use, it seems that there is nothing big.

JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile);

String apiversion = rwb.getversion ();

? Methods provided by Sheet interface

String getName ()

Get the name of Sheet, example:

JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile);

JXL.SHEET RS = rwb.getsheet (0);

String sheetname = rs.getname ();

2. INT getColumns ()

Get the total number of columns included in the Sheet table, examples:

JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile);

JXL.SHEET RS = rwb.getsheet (0);

INT RSCOLUMNS = rs.getcolumns ();

3. Cell [] getColumn (int Column)

Get all the cells of a column, returns a cell object array, example:

JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile);

JXL.SHEET RS = rwb.getsheet (0);

Cell [] Cell = rs.getColumn (0);

4. INT getRows ()

Get the total number of lines contained in the Sheet table, examples:

JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile);

JXL.SHEET RS = rwb.getsheet (0);

Int rsRows = rs.getrows ();

5. Cell [] GetRow (int Row)

Get all the cells of a certain line, returning the cell object array, an example:

JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile);

JXL.SHEET RS = rwb.getsheet (0);

Cell [] Cell = rs.getrow (0);

6. Cell getcell (int column, int in)

Get the object reference to the specified cell, you need to pay attention to its two parameters, the first is the number of columns, the second is the number of rows, which is different from the usual row, the column combination is somewhat different. JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile);

JXL.SHEET RS = rwb.getsheet (0);

Cell Cell = rs.getcell (0, 0);

Generate new Excel work

The following code is mainly to introduce you how to generate a simple Excel worksheet, where the content of the cell is no modified (e.g., font, color, etc.), and all the content is written as a string. (Full code See Excelwriting.java)

Similar to reading the Excel worksheet, you should first create a Workbook object using the factory method of the Workbook class. It should be noted here that it can only create Workbook through the factory method provided by the API, and cannot be used Writableworkbook constructor constructor because the constructor of the class WritableWorkbook is the protected type. The sample code snippet is as follows:

Import java.io. *;

Import jxl. *;

Import jxl.write. *;

... ...

Try

{

// Build a Workbook object, read-only Workbook object

//Method 1: Create a writable Excel workbook

Jxl.write.writableworkbook wwb = workbook.createworkbook (new file (targetfile);

//Method 2: Writing WritableWorkbook directly to output flow

/ *

OutputStream OS = New FileoutputStream (TargetFile);

JXL.WRITE.WRITABLEWORK WWB = Workbook.createworkbook (OS);

* /

}

Catch (Exception E)

{

E.PrintStackTrace ();

}

The API provides two ways to process the writable output stream. One is to generate a local file. If the file name does not have a full path, the default file is positioned in the current directory, if the file name has a full path The generated Excel file is positioned in the corresponding directory; another is to write the Excel object directly to the output stream, for example: the user accesses the web server through the browser, if the HTTP header is set correctly, the browser is automatically called The client's Excel application displays the dynamically generated Excel spreadsheet.

The next step is to create a worksheet, the method of creating a worksheet is almost the same as the method of creating a work, and the corresponding object is also obtained through the factory mode method. This method requires two parameters, one is the name of the worksheet, the other is The worksheet is in the position of the work, refer to the following code snippet:

File: // Create an Excel worksheet

JXL.WRITE.WRITABLESHEET WS = WWB.CREATESHEET ("Test Sheet 1", 0);

"This pot is also supported, the materials are also ready, you can start the pot!", Now you have to do it is just the EXCEL basic data type provided by the API, and add them to the worksheet. Refer to the following code segment:

File: // 1 /. Add label object

Jxl.write.label labelc = new jxl.write.label (0, 0, "this is a label cell"); ws.addcell (labelc);

// Add object with a font formatting

Jxl.write.writablefont wf = new jxl.write.writablefont (WritableFont.Times, 18,

Writablefont.bold, true);

Jxl.write.writablecellformat wcff = new jxl.write.writablecellformat (wf);

JXL.WRITE.Label labelcf = new jxl.write.label (1, 0, "this is a label cell", WCFF);

WS.Addcell (labelcf);

// Add object with font color formatting

JXL.WRITE.WRITABLEFONT WFC = New JXL.WRITE.WRITABLEFONT (WritableFont.arial, 10,

Writablefont.no_bold, false,

Underlinestyle.no_underline, jxl.format.colour.red;

JXL.WRITE.WRITABECECELLFORMAT WCFFC = New JXL.WRITE.WRITABECECELLFORMAT (WFC);

JXL.WRITE.Label labelcfc = new jxl.write.label (1, 0, "this is a label cell", WCFFC);

WS.Addcell (labelcf);

// 2. Add Number object

Jxl.write.number labeln = new jxl.write.Number (0, 1, 3.1415926);

WS.Addcell (labeln);

// Add Number object with formatting

JXL.WRITE.NUMBERFORMAT NF = New jxl.write.Numberformat ("#. ##");

JXL.WRITE.WRITABLECELLFORMAT WCFN = New JXL.WRITE.WRITABECELLFORMAT (NF);

Jxl.write.number labelnf = new jxl.write.Number (1, 1, 3.1415926, wcfn);

WS.Addcell (labelnf);

// 3. Add Boolean object

Jxl.write.Boolean labelb = new jxl.write.Boolean (0, 2, false);

WS.Addcell (labelb);

// 4. Add a DateTime object

Jxl.write.datetime labeldt = new jxl.write.datetime (0, 3, new java.util.date ());

WS.Addcell (labeldt);

// Add a DateFormat object with formatting

JXL.WRITE.DATEFORMAT DF = New JXL.WRITE.DATEFORMAT ("DD MM YYYY HH: MM: SS");

JXL.WRITE.WRITABECECELLFORMAT WCFDF = New JXL.WRITE.WRITABECELLFORMAT (DF);

Jxl.write.datetime labeldtf = new jxl.write.datetime (1, 3, new java.util.date (), wcfdf);

Ws.addcell (labeldtf); there are two points to caus you to pay attention. The first point, when constructing the cell, the location of the cell in the worksheet has been determined. Once created, the location of the cell cannot be changed, although the content of the cell can be changed. In the second point, the positioning of the cell is the following regularity (COLUMN, ROW), and the subscript starts from 0, for example, A1 is stored in (0, 0), B1 is stored (1, 0) .

Finally, don't forget to close the open Excel workmail object to release the occupied memory, see the following code snippet:

File: // Write EXEL Worksheet

Wwb.write ();

// Close Excel work thin object

WWB.CLOSE ();

This may have little different from the operation of reading the Excel file. Before shutting down the Excel object, you must call the Write () method first, because the previous operation is stored in the cache, so the content to operate through this method Save in the file. If you turn off the Excel object first, you can only get an empty work.

Copy, update Excel work

Next, I will introduce how to update an existing work, mainly the following two steps, the first step is to construct a read-only Excel work, the second step is to create new writable with the Excel workstorm that has been created. Excel works thin, refer to the following code snippet: (complete code see ExcelModifying.java)

File: // Create a read-only Excel work thin object

JXL.Workbook RW = jxl.workbook.getWorkbook (New file (sourcefile);

// Create a writable Excel work thin object

JXL.WRITE.WRITABLEWORKBOOK WWB = Workbook.createworkbook (New File (Targetfile), RW);

// Read the first work list

JXL.WRITE.WRITABLESHEET WS = WWB.GETSHEET (0);

// Get the first cell object

JXL.WRITE.WRITABECECELL WC = Ws.GetwritableCell (0, 0);

/ / Judgment the type of cell, make corresponding transformation

IF (wc.gettype () == CellType.label

{

Label L = (label) WC;

L.Setstring ("The Value Has Been Modified.");

}

// Write an Excel object

Wwb.write ();

// Close the writable Excel object

WWB.CLOSE ();

// Close the read-only Excel object

Rw.close ();

The reason why to build an Excel object is completely due to efficiency because the above example is the main application of the API. In order to improve performance, when reading a worksheet, some of the output information related to the data, all format information, such as: font, color, etc. are not processed, because our purpose is to get the value of row data, both There is no modification, nor does it affect the value of the value. The only unfavorable thing is that in memory will save both the same worksheet, so when the worksheet is large, it will occupy a considerable amount of memory, but now the size of memory is not a key factor.

Once you have a writable worksheet object, we can update the cell object, where we do not have to call the ADD () method provided by the API, because the cell has been in the worksheet, so we only need To call the corresponding setxxxx () method, you can complete the update operation.

Using the original formatted modification of the cells cannot be removed, we can also add new units to make the content of the cells in different forms.

The newly generated worksheet object is writable. In addition to updating the original unit, you can add a new cell to a worksheet, which is exactly the same as the operation of Example 2.

Finally, don't forget to call the Write () method, write the updated content into the file, then turn off the workmaking object, here there are two working thin objects to be turned off, one is read-only, and the other is writable.

The following is a simple example of creating a matrix in an Excel form:

Import org.apache.poi.hssf.usermodel. *;

Import java.io.fileoutputstream;

// Code Run Against the Jakarta-Poi-1.5.0-final-20020506.jar.

Public class poitest {

Static public void main (string [] args) throws exception {

FileOutputStream Fos = New FileOutputStream ("foo.xls");

HSSFWORKBOOK WB = New HSSFWORKBOOK ();

HSSFSHEET S = Wb.createsheet ();

Wb.setsheetname (0, "matrix");

For (Short I = 0; I <50; i ) {

HSSFROW ROW = S.CREATEROW (i);

For (Short J = 0; J <50; J ) {

HSSFCell Cell = row.createcell (j);

Cell.setcellValue (" i ", " J);

}

}

Wb.write (fos);

Fos.close ();

}

}

This code first creates a Workbook, get a table, name, and then write, then write into a 50X50 matrix. Finally output an Excel file called foo.xls, or even on the Apple Mac machine.

The POI project is an exciting step of Java applications, providing users with new features of Windows document integration, allowing Java developers to easily expand their products.

From:

Humanc2d4,

Time: 2003-5-16 14:49:00,

ID: 1867310

I said the way to send and receive email in Java (reproduced from: Java lovers)

This article discusses how to use Java to write the Java Applet that can send and receive E-mail according to SMTP and POP3 protocols.

One. Java network programming initial

1. Establish TCP / IP connection

Constructor Socket (String Host, INT Port) in the Socket class is used to create a socket and connect to the specified host (Host) and port (port). The host name cannot be specified by the Java Applet safety mechanism, and the name of the host in which the called Applet is located is the same. Therefore, you can get the URL of the Class file currently read by the browser first by the getCodeBase method, and then returns the name of the host represented by the string from the URL by the gethost method. For example from

Http://person.zj.cninfo.net/~caveman/ This URL can return to the hostname "Person.zj.cninfo.Net" represented by the string.

Regarding the value of the standard port address is generally: SMTP is 25, POP3 is 110, FTP is 21, etc., of course, some hosts are used by non-standard ports, it is best to determine it before use.

2. Data transmission and reception

The GetOutputStream method in the Socket class can obtain the output data stream corresponding to the current Socket, and write the data into the output data stream with the WriteBytes method in the DataOutputStream class.

Using the GetInputStream method in the Socket class, you can get the input data stream corresponding to the current Socket, with the Readline method in the DataInputStream class, can read the data in the input data stream.

3. Turn off TCP / IP connection

The TCP / IP connection can be turned off in the CLOSE method in the Socket class.

two. SMTP protocol Send E-mail Java Applet

1. SMTP protocol and server

The SMTP (Simple Mail Transfer Protocol) protocol is currently popular online, and there are 14 commands in the SMTP protocol. However, it is sufficient to send an E-mail only need to use the following 5 commands (see Table 1).

Table 1

Leading function

Helo shakes hands with the SMTP server to transfer this domain name

Mail from: Transfer sender's mailbox name

RCPT to: Transfer recipient's mailbox name

Data Send letter data (including letterhead and letter)

Quit Exits the connection to the SMTP server

In addition to the SMTP server provided by ISP, some SMTP ports of the server stored for free personal homepage are also open. If the server does not increase the RELAY limit (such as Netease Nease.net), then It can be used as a SMTP server. Such as Person.zj.cninfo.net, etc., put a Java applet to be compiled and call it on these servers, and users can send E-mail online.

2. Main procedures in SMTPTester.java

The Java Applet uses three TextField components TF1, TF2, and TF3, which are used to enter the user's mailbox name, the recipient's mailbox name, and the title of the letter; also used two text districts ( TEXTAREA) Parts TA1 and TA2, TA1 For users to enter the letter content, TA2 is used to display the response information and error information of the SMTP server; of course, a button (Button component bu 1. After the user enters the correct information, use the mouse Click on it, the letters can be sent out.

Event capture handler See programs 1:

Public Boolean Handleevent (Event Event1) {

IF ((Event1.target! = BU1) || (Event1.id! = 1001)))

/ * If not the button BU1 is pressed by the mouse * /

{

Return False;

}

IF ((tf1.gettext (). Length ()! = 0) && (tf2.gettext (). Length ()! = 0))

/ * If the sender name of the sender and the recipient is filled, execute the sender bu1run * /

{bu1.disable ();

Bu1run ();

Return True;

}

Else {

TA2.AppendText ("Please give me enough information to send your email! / n"); return true;

}

(Program 1)

Send E-mail programs bu1run see programs 2:

Public void bu1run () {

Try {

Socket Socket1 = New Socket (). Gethost (), 25);

/ * Establish connection with the SMTP server * /

DataOutputStream DataOut2 = New DataOutputStream (Socket1.getOutputStream ());

DataInputStream DataIN3 = New DataInputStream (Socket1.GetInputStream ());

GetReply (DataIn3);

Dataout2.writebytes ("Helo Person.zj.cninfo.net/r/N");

/ * Started by SMTP protocol * /

GetReply (DataIn3);

DataOut2.writebytes ("Mail from:" TF1.GetText () "/ r / n");

GetReply (DataIn3);

DataOut2.writebytes ("RCPT TO:" TF2.Gettext () "/ r / n");

GetReply (DataIn3);

DataOut2.writebytes ("DATA / R / N");

GetReply (DataIn3);

DataOut2.writebytes ("from:" tf1.gettext () "/ r / n");

DataOut2.writebytes ("to:" tf2.gettext () "/ r / n");

Dataout2.writebytes ("Subject:" Tf3.Gettext () "/ n / n" Ta1.getText () "/ r / n. / r / n");

GetReply (DataIn3);

Dataout2.writebytes ("quit / r / n");

GetReply (DataIn3);

Socket1.close ();

/ * Exit connection * /

Bu1.enable ();

Return;

}

Catch (java.ioException ioException0) / * Capture IO error * /

{

TA2.AppendText ("Error! / N");

Bu1.enable ();

Return;

}

}

(Program 2)

Receive Server Answer GetReply See Program 3:

Void getReply (DataInputStream DataIn1)

{

String string2;

String2 = "";

Try

{

String2 = datain1.readline ();

TA2.AppendText (String2 "/ N");

}

Catch (java.io ioexception oException0)

{

TA2.AppendText ("Error! / N");

Bu1.enable ();

Return;

}

}

(Program 3)

3. Instance operation

in

Http://person.zj.cninfo.net/~caveman has already put compiled SMTPTester.class and calling it SMTP.htm, Figure 1 is the applet at the time of running, then this letter has been Send to caveman@nese.net! three. POP3 protocol reading E_mail's Java Applet

1. POP3 protocol and server

POP3 (Post Office Protocol Version 3) is a commonly used network protocol for collecting E_MAIL from the mailbox of the remote server, and its common commands are:

(1) Authorization State

User User Name

Pass User Password

Quit Exit

(2) Transaction State

STAT Mailbox status, that is, a few letters in the mailbox, a total of a total size (8 binding), etc.

List Displays the size of the per letter when the MSG parameter is displayed, and the length of the letter numbered MSG is displayed with the MSG parameter (8).

TOP Take the header (Head) and part of the letter (body), n = 0, N ≠ 0, N ≠ 0 The front N row of the letter. This command is an optional command, and some POP3 server software does not support it.

Retr reads a letter previously numbered MSG.

Dele Deleting a letter to an MSG, in fact, is only a tag, truly deleting an update status.

(3) Update State)

Quit Exited and deleted mail that DELE tagged.

There are also NOOP, LAST, RSET, RPOP and other commands.

Similar to the SMTP server, in addition to the POP3 server provided by ISP, some of the domestic storage of free personal homepage is also available (such as Netease Nease.Net). Users can also get a POP3 mailbox while getting free homepage, such as my mailbox for caveman@nease.net, put a copy of the applet you want to write and call it on the server, run it online, enter the correct user After the name and password, you can read E-Mail.

2. Main procedures in pop3tester.java

The Java applet has a total of three textfield components TF1, TF2, and TF3, which are used to enter user names, passwords, and numbers (0 when 0, only the letter of the mailbox status " Reading letter); also uses a textarea component TA2 to display the answer information of the POP3 server, letters content, and error information. Of course, a button (Button component bu1, the user enters the correct information) , Click on it with a mouse to read the specified letter.

The event capture handler is the same as the SMTPTester, read the E-mail program bu1Run see the program 4:

Public void bu1run ()

{

Try

{

Socket Socket1 = New Socket (GetCodeBase (). Gethost (), 110); / * Connect POP3 Server * /

DataOutputStream DataOut2 = New DataOutputStream (Socket1.getOutputStream ());

DataInputStream DataIN3 = New DataInputStream (Socket1.GetInputStream ());

GetReply (DataIn3);

Dataout2.writebytes ("User" Tf1.Gettext () "/ r / n");

GetReply (DataIn3);

DataOut2.writebytes ("pass" tf2.gettext () "/ r / n");

GetReply (DataIn3);

DataOut2.writebytes ("STAT / R / N");

/ * Mail box status * /

GetReply (DataIn3);

DataOut2.writebytes ("List / R / N");

/ * Letter length list * /

GetReply2 (Datain3);

TA2.AppendText ("/ n");

IF (tf3.gettext (). Equals ("0") == false)

{

DataOut2.writebytes ("retr" tf3.gettext () "/ r / n");

/ * Read Specify Letters * /

GetReply2 (Datain3);

TA2.AppendText ("/ n");

}

Dataout2.writebytes ("quit / r / n");

GetReply (DataIn3);

Socket1.close ();

Bu1.enable ();

Return;

}

Catch (java.io ioexception oException0)

{

TA2.AppendText ("Error! / N");

Bu1.enable ();

Return;

}

}

(Program 4)

Receive Server Answer GetReply and getReply2 See programs 5:

Void getReply2 (DataInputStream DataIn1)

{

String string2;

String2 = "";

Try

{

FOR (String2 = DataIn1.readline ();

String2.equals (".") = false;

String2 = datain1.readline ())

/ * List and retri commands have multiple lines, but they all use a sentence "." As the end, according to this pickup information * /

{

TA2.AppendText (String2 "/ N");

}

}

Catch (java.io ioexception oException0)

{

TA2.AppendText ("Error! / N");

Bu1.enable ();

Return;

}

}

(Procedure 5)

Read the same procedures in the single sentence response, the same, because when dialogue with the POP3 server, there is a getReply2 program to handle this problem.

3. Instance operation

in

Http://www.netese.com/~caveman has already put compiled POP3TESTER.CLASS and calls it POP3.html, Figure 2 is the screen when the applet is running, just on Person.zj.cninfo.net The letter sent by SMTPTester has reached the mailbox of my Netease. four. Program improvement

The above two Java Applets are also very imperfect, and there is still a lot of places that need to be improved on the support of the wrong capture. In addition, according to some of the basic methods mentioned above, simply change, other network protocols, such as FTP, News, etc.

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

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.034, SQL: 9