Several methods of accessing program status - Java IO application talks

xiaoxiao2021-03-06  22

Jungleford is like

It has not been taken from Blog for more than a month. For example, the projects of the laboratory are collecting work, huge, such as finding work and related things; and in February is to accompany the old man, the speed of the family It is imaginable that ... but mainly did not find a suitable Topic, or this time is lazy (Proqi syndrome), net is watching the "Hanwu Emperor" and historical books, and other messy Jiaste, just play Java seriously, haha! Now work is almost implemented, so good is not too bad, and the life of the small-breasted young Jungleford starts to enter the right track! The above is some nonsense in the New Year. Today, I will talk about "program status saving" aspects. We can easily think of "serialization" (serialization, and "sequentialization" or "serialization", but "serial" The word always let me think of communication and hardware interface, so I am more accustomed to "serialization" called, let alone this name is coming, and I will talk about the origin of this name), of course, serialization It is a convenient and effective data access method, but it also has a wider range of applications. In general, it is to discuss some of I / O applications.

File I / O: Files → Serialization

★ File stream file operation is the simplest and most exclusive way, we said that the file operation is not just a "naked" way through FileInputStream / FileOutputStream to write data directly to the local file (like I used to write A mine-mine game Javamine is to save a state of the situation, which is compared to the "underlying".

Main Class and Method Description FileInputStream.Read () Read Data Data from Local File FileReader.Read () Readput (text) Data FileoutputStream.write () Save Binary Data to Local File FileWriter.write () Save Character Data to Local Files

★ XML and the above simple I / O mode, XML look much "high-grade", so that it is a standard for data exchange. Take the DOM way, it cares about constructing a document tree in memory, and the data is saved on a node (which can be a leaf node, or the attribute of the label node), the construction of the next one Write an external file, but we only need to know the location of the file, do not know how I / O operation, the XML operation method may also practice more people, so only list related methods, for beginners Learn about. The main package is javax.xml.parsers, org.w3c.dom, javax.xml.transform.

The main classes and methods described DocumentBuilderFactory.newDocumentBuilder (). Parse () parsing an external XML file, to obtain a tree of DOM Document object DocumentBuilderFactory.newInstance (). NewDocumentBuilder (). NewDocument () to initialize a DOM tree Document.getDocumentElement ( ). Appendchild () Add a sub-node to a tag node Document.createTextNode () Generate a string node node.getChildNodes () get a node all the next layer node.removeChild () Delete Subnation Document. GetElementsBytagname () Find all the tag nodes of all specified names Document.getElementById () Find a tag node of the specified name, if there is a plurality of conformity, return to one, usually the first Element.getaTribute () gets a value of a label Element.setttribute () Sets the value of a label for Element.RemoveAttribute () deletes a tag for a property transformerfactory.newinStance (). NewTransformer () .transform () Write a DOM tree into an external XML file ★ Serialization uses basic file read and write mode access data, if we only save the same type of data, you can save it in the same format, for example When I saved a disk in my javamine, you need to save each checkered coordinate, whether there is mine, whether it is opened, etc., which combines these information into a "composite type"; reverse, if there are a variety of different types of data, Then we either break it into a number of parts, saved with the same type (such as String), or we need to add logic that resolves different types of data formats in the program, which is inconvenient. So we expect to handle data with a higher level of "high" level, programmers should resolve data as little time and code, in fact, serialization operations provide us with such a way. Serialization may have contact, which can write objects in a particular coded format or read from external byte streams (ie ObjectInputStream / ObjectOutputStream). Serialized an object is very simple, just implement the serializable interface, or even use it for it to add any way:

Public class myserial imports java.io.serializable {...}

But there is a condition: that is, you have to serialize, each attribute must be "sequentially". This sentence is a bit 拗, in fact, all basic types (which are int, char, boolean, "can be sequentially", and you can look at the JDK documentation, will find that many classes have already implemented serializable (ie It is already "sequential"), so these types of objects and basic data types can be directly used as internal properties that you need sequence. What should I do if I have encountered an attribute of "sequentialization"? Sorry, the class of this property also needs to implement the Serializable interface in advance, so that all attributes are "sequentially".

Main Class and Method Description ObjectOutputStream.WriteObject () Sequence an object to external byte stream ObjectInputStream.readObject () read from external byte stream and restructuring the object from the actual application, "serializable" interface is not Define any way, as if it is just a tag (or a keyword like Java), once the virtual machine sees this "tag", try calling the pre-predefined serialization mechanism unless you are implementing the Serializable interface The private readObject () or WriteObject () method is also defined. This is very strange. But if you are not willing to let the system use the default way to serialize, you must define the two methods mentioned above:

public class MySerial implements java.io.Serializable {private void writeObject (java.io.ObjectOutputStream out) throws IOException {...} private void readObject (java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {...} .. }

For example, you can call the default serialization method ObjectOutputStream.defaultWriteObject () in WriteObject (); for example, you don't want to use some sensitive properties and information serialization, you can also call the objectOutputStream.writeObject () method to clearly specify the needs. Serialized those properties. With regard to user customized serialization, we will mention later.

★ The serialization above the bean is just a basic application. After you sequence the object to the external file, open the file with notepad, you can only guess this is about this class from some readable characters. Document, this requires you to be familiar with the byte coding method of serialized files, which will be more painful (in the first volume of "Core Java 2", if you are interested, you can check the reference information, some cases We may need to be serialized with better readability. On the other hand, as the core concept "javabeans" as a Java component, starting from JDK 1.4, the "long-term persistence" (long-term persistence "(long-term persistence" is required to support text mode is also required. Open the JDK document, there is a class named "Encoder" in the java.beans package, which is a practical class that can serialize the bean. And it is related to the two major classes with XMlecoder and Xmldecoder, apparently, which is a tool for saving and reading Bean with XML file format. Their usage is also very simple, and it is similar to ObjectOutputStream / ObjectInputStream / ObjectInputStream.

Main Class and Method Description XmlenCoder.writeObject () Sequence an object to external byte stream Xmldecoder.ReadObject () read from external byte stream and restructively

If a bean is in the following format:

Public class mybean {INT i; char [] c; string s; ... (GET and SET operation omitted) ...}

Then the XML file serialized through XMlecoder has this form:

a B c < / void> fox jump! Many visual components like AWT and SWING are bean, of course, can be used Sequence is serialized, the following is an XML file after the JFRAME serialization extracted from the JDK document:

frame1 0 0 200 hello true therefore, the data you want to save is some words that are not too complicated, and it is not a convenient choice for BEAN re-serialization. ★ Properties mentioned in a small article on the collection framework before, Properties is a typical example of the historical collection class. It is mainly not introducing its collection characteristics. Everyone may always touch some configuration files, such as Windows INI files, Apache's conf files, and Properties files in Java, which are saved in the "keyword-value" mode. The concept of "environment variable" knows it, it is also a "key-value" right. It used to see the "How to get a certain information" in the version, in fact, there are many saved in the environment variables. , As long as one

System.getProperties (). List (system.out);

A list of all environment variables can be obtained:

- Listing Properties --Java.Runtime.name = Java (TM) 2 Runtime Environment, Stand ... Sun.boot.library.path = C: / Program Files / Java / J2re1.4.2_05 / binjava.vm.version = 1.4.2_05-b04java.vm.vendor = sun microsystems incapacity = sun microsystems incapacity = sun microsystems inc. encoding.pkg = sun.iouser.country = CNsun.os.patch.level = Service Pack 1java.vm.specification.name = Java Virtual Machine Specificationuser.dir = d: / my documents / projects /eclipse/SWTDemojava.runtime.version = 1.4.2_05-b04java.awt.graphicsenv = sun.awt.win32graphicsenvironmentjava.ndorsed.dirs = C: / Program files / java / j2re1.4.2_05 / li ... Os.Arch = x86java.io.tmpdir = C: /Docume ~1/cn2lx0Q0/locals ~ 1/temp/line.separator=java.vm.Specification.vendor=Sun microsystems inc.user.variant = os.name = windows xpsun.java2d.fontpath = java.library.path = C: / Program Files / Java / j2re1.4.2_05 / bi ... java.specification.name = Java Platform API Specificationjava.class.version = 48.0java.util.prefs.PreferencesFactory = java.util.prefs.WindowsPreferences Fac ... os.version = 5.1user.home = D: /Users/cn2lx0q0user.timezone=java.awt.printerjob=sun.awt.windows.WPrinterJobfile.encoding=GBKjava.specification.version=1.4user.name=cn2lx0q0java .class.path = d: / my documents / project / Eclipse/swtdemo/bi...java.vm.Specification.Version=1.0sun.arch.data.model=32java.home=c:/program files / java / j2re1.4.2_05java.specification.vendor = Sun Microsystems Inc.user.language = zhawt.toolkit = sun.awt.windows.WToolkitjava.vm.info = mixed modejava.version = 1.4.2_05java.ext.dirs = C: / Program FILES / JAVA / J2RE 1.4.2_05 / li ... sun.boot.class.path =

C: / program files / java / j2re1.4.2_05 / li ... java.vendor = sun microsystems inc.file.separator = / java.vendor.url.bug = http: //java.sun.com/cgi- BIN / BUGREPORT ... Sun.cpu.endian = LitTlesun.io.Unicode.Encoding = unicodelittlesun.cpu.isalist = Pentium i486 i386 Main class and method description LOAD () Save attribute from an external stream attribute Store () To external stream (especially file) getProperty () gets a specified property setProperty () Sets a specified property list () lists all "key-value" containing this Properties object to system.getproperties () gets the system. Environment variable

You can save a Properties file like this:

Properties Prop = New Properties (); Prop.SetProperty ("Key1", "Value1"); ... fileoutputstream out = new fileoutputstream ("config.properties"); prop.store (out, "- here is a file header , Can join the comment - ");

★ preferences If I say that Java can do not use JNI means to operate Windows registration form, do you believe it? Many software men have options such as "setting" or "preferences" to set or modify the software configuration, which can be saved to a configuration file as described above, if it is a Windows platform, May be saved in the system registry. Starting from JDK 1.4, Java joined a Java.util.PREFS package that handles users and system configuration information under Java.util, one of which type Preferences is a comparison of "advanced". In essence, Preferences itself is a platform-independent thing, but different OS is related to its SPI (Service Provider Interface), so you may see the preferences in different systems. Saved as local files, LDAP directory entries, database entries, etc., as in Windows platform, it saves to the system registry. Not only that, you can also export the preferences to an XML file or import from an XML file.

The main class and method description SYSTEMNODEFORPACKAGE () gets a Preferences object according to the specified Class object, the registry path of this object is SYSTEMROOT () starting from "HKEY_LOCAL_MACHINE /" to get the registry path hkey_local_machine / software / javasoft / prefs for root knots Point preferences object UserNodeforPackage () Get a Preferences object according to the specified Class object, the registry path of this object is Userroot () starting from "HKEY_CURRENT_USER /" to get the registry path hkey_current_user / soft / javasoft / prefs for root node The preferences object PUTXXXX () sets the value of an attribute, where xxx can be a basic numeric type, such as int, long, but the first letter is capitalized, indicating that the parameter is the corresponding type, or it can be used directly with PUT, parameter Get a value of the character string getxxx () ExportNode () Export all preferences to an XML file exportsubtree () Export some preferences to an XML file ImportPreferences () From the XML file Import preferences You can save as follows data:

Preferences myprefs1 = preferences.Usernodeforpackage (this); // This method is to establish a registry key in the current class by "HKEY_CURRENT_USER /" to create a registry key preferences myprefs2 = preferences.systemnodeforpage (this); // This method is "" HKEY_LOCAL_MACHINE / "Under the current class path, establish a registry key preferences myprefs3 = preferences.userroot (). Node (" com.jungleford.deemo); // This method is "HKEY_CURRENT_USER / SOFTWARE / JavaSoft / prefs / "Under the path" COM / Jungleford / Demo ", establish a registry key preferences myprefs4 = preferences.systemroot (). Node (" com.jungleford.demo "); // This method is in" HKEY_LOCAL_MACHINE / SOFTWARE / JAVASOFT / Prefs / "Press" COM / JUNGLEFORD / DEMO "to establish a registry key myprefs1.putint (" key1 ", 10); myprefs1.putdouble (" key2 ", -7.15); myprefs1.put (" key3 " , "value3"); fileoutputstream out = new fileoutputstream ("prefs.xml"); myprefs1.exportNode (OUT);

Network I / O: Socket → RMI

★ Socket Socket programming may be very familiar, so there is not much discussion, but it is worth considering by saving data to remote servers through Socket or reading data from network socket. ★ The RMI RMI mechanism is actually the Java version of RPC (remote procedure), which uses socket as basic transmission means, and is also the most important application of serialization. Now online transmission is basically in a stream from a programming perspective. Socket is an example that converts an object to one-by-line stream to facilitate network transmission. Imagine the program design in the traditional stand-alone environment, the parameter transfer for the Java language function (Note), there will be two cases: if it is the basic data type, in this case The same is the same as the C language, and the value is transmitted; if it is an object, it is passed the reference to the object, including the return value is also referenced, not a complete object copy! Imagine method call between different virtual machines, even two identical types of objects, they are also very likely to be different! In addition, for the method calling process, since the memory "field" is fully being occupied by the caller, when the call method is returned, the caller's address is returned to the program counter (PC), and recovers the caller State, if it is two virtual machines, it is not possible to save the status of the caller with a simple stack. For various reasons, we need to establish a "agent" object between the RMI communication entity, such as "stub", which is equivalent to the agent on the client, Stub is this, of course, this is a later words. Local objects and remote objects (not necessarily different machines in the physical location, as long as they are not transmitting parameters and return values ​​between "remote") in the same virtual machine, there may be such a few scenarios: Value delivery: This includes Two kinds of sites: If it is the basic data type, it is "sequentially", all serialized into transmitable byte streams; if it is an object, and is not a "remote object" (so-called "remote object" is implemented Java .rmi.Remote Interface object), the objective passed should be referenced, but due to the above reasons, the reference is not enough to prove the identity of the object, so the transfer is still a serialized copy (of course this object must also meet the above " Conditional conditions). Quote Transfer: You can only be "remote object" that can be referenced. Here, the so-called "reference" does not understand it is really just a symbol. It is actually a mirror like a real object on the remote server! Just because it is a bit "privilege" (no need to pass serialization), there is an instance in local memory, which is actually this "twins". It can be seen that the serialization has an important position in RMI.

Database I / O: CMP, Hibernate

★ What is "Persistence" to use VMware friends probably know when a guest OS is running, click "Suspend" to hang the virtual OS, which will save the entire virtual memory to disk, such as your virtual OS Assigned 128M running memory, then you will find a 128M file in the directory where you are in the virtual OS, this is the full image of virtual OS memory! This mirroring means of this memory is actually the origin of "Persistence" concept. ★ CMP and Hibernate Because I am not too familiar with J2EE, I will find some material to see, so I am worried that I don't have a specific summary this time. People want to learn ... it is a painful thing ~~ ~> _ <~~~ serialization and then discuss

From the above discussion, we are not difficult to experience, serialization is an important foundation for Java's two major selling points - Distributed and cross-platform (OS Independent). Tij (ie "Thinking In Java") When talking about the I / O system, the serialization is called "Lightweight Persistence" - "Lightweight Persistence", which is really interesting. ★ Why is it called "sequence"? I am more accustomed to "serialization" rather than "serialization" rather than "serialization" rather than "serialization". You will review some of the basic knowledge of computer before introducing this reason. We know that the memory space of modern computers is linearly addressable (what is "linear" knows, it is an element only has a unique "pre-drive" and the only "successful" Of course, the head tail element is an exception; for the address, it is certainly impossible to have two, otherwise it will be inserted), "Address", this concept is promoted to the data structure, which is equivalent to "pointer", this is Undergraduate is probably known. Note that since it is linear, the "address" can be seen as "serial number" in memory space, indicating that its organization is sequential, "serial number" or "serial number" is a "serialization" mechanism Available. Why do you say this? For example, we have two objects A and B, which are examples of classes A and B, which are sequentially, and A and B have an attribute of c, according to the principle we have said before, C Of course It must also be serialized.

Import java.io. *; ... class a imports serializable {c c; ...} Class B Implements Serializable {C C; ...} Class C Implements Serializable {...} a a; b; c C1; ...

Note that when we instantiate A and B, we deliberately let their C attributes use the same C property reference, such as C1, then please try it, but we serialize A and B, their C attributes Is a copy or two copies in the external byte stream (of course, not just a file)? Serialization This is a scheme similar to "pointer": it is a "serial number" for each serialized object, but when it is sequenced, if it is The attribute object is already serialized, then the serial number of the attribute is only written to the output stream; when the sequence-serialized object is recovered, the corresponding stream is found according to the serial number to recover. This is the origin of the "serialization" name! Here we see "serialization" and "pointer" are extremely similar, but "pointer" is an address chain of memory space, and serialization is "serial chain" in the external stream. Use "serial number" instead of memory addresses to identify a serialized object because the address is restored from the stream to memory, and its address may not be the original address - we need only the reference between these objects Relationship, not the original position of the dead, this is necessary in RMI, transmitting objects (flows) between two different machines, simply impossible to have the same memory address on both machines.

★ More flexible "serialization": Transient property and Externalizable Serializable is really convenient, so that you can easily save objects in memory to the outside. However, there are two problems that make the power of serializable receipt: one is an efficiency problem, "Core Java 2" pointed out that Serializable Using the system default serialization mechanism affects the running speed of the software, because the reference number required for each property And the quotation number, plus the I / O operation (I / O and memory readout, but a magnitude of the size), the price is of course considerable. Another trouble is "naked" serializable unmissible, stupid, give you sequence, no matter what you want to do. In fact, you can have at least three customized sequences. One of the previous places has been mentioned, it is to add a private WriteObject () and readObject () method in the class of the IMPLEMENTS SERIALIZABLE (this kind of serializable is not naked, ^ _ ^), in these two methods, this serialization What, don't be serialized, then you have told you, you can of course, you can call ObjectOutputStream.defaultWriteObject () and ObjectInputStream.defaultReadObject () still execute the default serialization action in these two methods. Don't do useless work on the code? Oh, you can use the objectOutputStream.WriteObject () and the ObjectInputStream.ReadObject () method to serialize the properties of your intention. But virtual machines see that you define these two methods, it will no longer use the default mechanism. If you don't let it serialize just to skip some properties, the above action seems to be troublesome, and the simpler method is to add the transient keyword to the property that does not want to serialize, indicating that it is a "transient variable", default serialization When you don't put these properties to the external stream. Of course, if you define the use of WriteObject () and readObject () methods, the transient variable can still serialize the transient variable. Exteriorism, keywords such as transient, violate, finally may not pay much attention, and now there are companies recruitment to ask questions: (any solution does not implement serializable and change to implement the Externalizable interface. We have studied the source code of these two interfaces and found that they are very similar, even confused. We have to remember: Externalizable defaults to save any object related information! Any save and recovery objects are defined by your own .Externalizable Method: Public void writeexternal (ObjectOutput out) throws oews oException; Public Void Readexternal (ObjectInput in) throws oews oewception, classnotfoundexception;

At first glance, this is almost almost almost almost, but Serializable and Externalizable are two different processes: SERIALIZABLE can use only external byte sequences only with external byte sequences. The object is rebuilt; however, externalizable is a rebuild that the default constructor (ie, the constructor that does not include the parameters) is called so that there is such an instance in memory, and then call the ReadExternal method to restore the properties in the instance. Therefore, if the attributes of the default constructor are not assigned in the readExternal method, they will be empty (NULL). It should be noted here that Transient can only be used in implementations of Serializable rather than Externalizable. ★ Serialization and Cloning From "Syndrome" recursive definition, a serialized object appears to be external clone of object memory images, and if there is no sharing of attributes, it should be a depth clone. About the topic of cloning can talk a lot, here is not well said, interested words can refer to IBM DeveloperWorks: Pointers in Java, reference and object's Clone

Little revelation

As an actual application, I have compared several ways to save Message objects when writing that simple mail client Jexp (mainly several critical properties and emails) to local methods, such as XML, Properties, etc. Finally, I have selected the way of serialization, because this method is the easiest, about, "learning to use". Here "Access Procedure Status" is actually just a primer topic, I want to say - just like the topic we discussed in front - in front of Java, you can have a lot of Solution: familiar files Operation, you may feel that Properties, XML or Bean is relatively convenient, then discovered that there is such a Dongdong, which probably "sky is a day", wait until you have contacted a lot of new methods, the result is " The same is true, re-reflecting the SERIALIZATION mechanism itself. This is not only Java, and science is also the same.

Reference

Core Java 2. by Cay S. Horstmann, Gary Cornell J2SE Adv. By JavaResearch.org Thinking in Java. By Bruce Eckel J2SE 1.4.2 Documentation. By java.sun.com Java Network Programming. By Elliotte R. Harold Java distribution Object: RMI and CORBA. By IBM DeveloperWorks

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

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