Several methods of accessing program status - Java IO application talks

xiaoxiao2021-03-06  17

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 methods and description

FILEINPUTSTREAM.READ () // Read Data FileReader.Read () // from a local file (text) data fileoutputstream.write () // saves binary data to local files 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

. Main class and methods and description

DocumentBuilderFactory.newDocumentBuilder (). Parse () // parse an external XML file, get a DOM Document object tree DocumentBuilderFactory.newInstance (). NewDocumentBuilder (). NewDocument () // initialize a DOM tree Document.getDocumentElement () .appendchild () / / Add a sub-node Document.createTextNode () / / generated a string node.getChildNodes () // Node Node Node Node.GetIldNodes () .removechild () / / Delete a node node Document.GtelementsByTagName () finds all the tag nodes of all specified names Document.getElementById () // find a label node that specifies the name, if there are multiple conformity, Then return to a certain one, usually the first element.gettribute () // Value of a value of a label Element.setttribute () // Set a value of a label Element.RemoveAttribute () / / Delete a property of a label 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 with the same format. For example, when saving a disc in my javamine, you need to save every checkered Coordinates, whether there is mine, whether it is open, etc., these information is combined into a "composite type"; the opposite, if there are multiple different types of data, then we either break down into several parts, with the same type (such as string) Save, either we need to add logic that resolves different types of data formats in the program, which is very 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, you may have access, it can write objects in a particular coding format or from external byte stream (ie ObjectInputStream

/

ObjectOutputStream

Read. 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 methods and description

ObjectOutputStream.writeObject () // sequence an object to external byte stream ObjectInputStream.readObject () // read and restructively object from external byte stream

From the actual application, "serializable" interface does not define any way, as if it is just a tag (or a keyword like Java), once the virtual machine sees this "tag", it will try to call itself A predefined serialization mechanism unless you also define a private readObject () or WriteObject () method while implementing the Serializable interface. 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 in the writeObject () above WriteObject ().

DEFAULTWRITEOBJECT (); if you don't want to sequence some sensitive properties and information, you can also call the ObjectOutputStream.WriteObject () method to explicitly specify those properties that require sequencement. 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 encoding method of serialization file, which will be more painful (in

"Core Java 2" first volume

The relevant coding method is mentioned. If you are interested, you can check the references), in some cases, we may need to be serialized with better readability. On the other hand, as a core concept of Java components

Javabeans

"From JDK 1.4," long-term persistence "(long-term persistence) is also required in its specification. Open

JDK documentation

,

Java.beans package

There is a famous ""

ENCODER

"The class, this is a practical class that can serialize the bean. The two main classes related to it have

XMLCODER

with

XMLDecoder

Obviously, this is a tool for saving and reading Bean with an XML file format. Their usage is also very simple, and it is similar to ObjectOutputStream / ObjectInputStream / ObjectInputStream. Main class and methods and description

Xmlencoder.writeObject () // Sequence an object to external byte stream Xmldecoder.ReadObject () // read and restructively object from external byte stream

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 such a form: 1 < Void index = "0"> a b C fox jump! like AWT

with

Swing

Many visual components are beans, of course, can be serialized in this way, and below is an excerpt from the JDK document

JFrame

XML file after serialization: frame1 < Object class = "javax.swing.jbutton"> Hello true therefore, the data you want to save is some words that are not too complicated, and it is not a kind of bean. Convenient choice. ★ Properties mentioned in the small articles on the collection framework before, Properties

It is a typical example of a historical set class, which 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: - listing property --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 incaps java.vendor.URL = http: //java.sun.com/path.separator=; java.vm.name = Java HotSpot (TM) Client VMfile.encoding.pkg = sun.iouser.country = CNsun.os.patch.level = Service Pack 1java.vm.specification.name = Java Virtual Machine Specificationuser.dir = d: / my documents / project /eclipse/SWTDemojava.runtime.version=1.4.2_05-b04java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironmentjava.endorsed.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.win dowsPreferencesFac ... 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 and description LOAD () // Take the attribute Store () from an external stream // Save the property to an external stream (especially file) getProperty () // get a specified property setProperty () // Set a specified attribute list () // listing all of this Properties object included all "key-value "Take system.getproperties () // acquired system current environment variables

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 is

Java.util

Enter a dedicated user and system configuration information

Java.util.prefs

One of the classes

Preferencees

It is a comparative "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. Main class and methods and description

SystemNodeForPackage () // Get a Preferences object according to the specified Class object, the registry path of this object is started from "HKEY_LOCAL_MACHINE /" to get the registry path hkey_local_machine / soft / javasoft / prefs for root node Preferences object usernodeforpackage () // Get a Preferences object according to the specified Class object, the registry path of this object is UserRoot () // starts from "HKEY_CURRENT_USER /" to get registry path hkey_current_user / soft / javasoft / prefs The preferences object PREFERENCES object PUTXXXXXXXXXXX () // sets the value of an attribute. Here XXX can be a basic numeric type, such as int, long, but the initial capital, indicating that the parameter is the corresponding type, or it can be directly With the PUT, the parameter is a string getxxx () // gets the value of the value exportNode () // exports all the preferences to an XML file exportsubtree () // export some preferences to an XML file ImportPreference () / / Import Preferences from XML File You can save the data as follows:

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. Sequence Discuss

From the discussion of the above technology, we don't really understand that serialization is an important foundation for the two major selling points of Java to achieve its advanical 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 "? This is really interesting. ★ Why is it called" Sequence "? I am more accustomed to it. "Serialization" is called "serialization" rather than "serialization". This is why you review some computer basic knowledge before introducing this reason. We know that the memory space of modern computers is linearly addressable. What is "linear" know, it is an element only having a unique "pre-drive" and the only "successive", of course, the head tail element is an exception; for the address, it is certainly impossible to have two, otherwise As far as the concept of "Address" is promoted to the data structure, it is equivalent to "pointer", this is probably known in the undergraduate lower grade. Note, since it is linear, "address" can be considered memory The "serial number" of the space indicates that its organization is sequential, "serial number" or "serial number" is an embodiment of "Serialization" mechanism. Why do you have two objects A and B, They are examples of classes A and B, which are sequentially sequentially, and A and B have an attribute of C, which is certainly sequentially sequentially based on the principles we have said before.

Import java.io. *; ... class a imports serializable {c c; ...} class b imports serializable {c c; ...} Class C imports serializable {...} a 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 address to identify a serialized object because the object is restored from the stream to memory, and its address may not be the original address. What we need is just a 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 is that the private WriteObject () and readObject () method adds private WriteObject () and readObject () methods in the type of IMPLEMENTS SERIALIZABLE (this serializable is not naked). In these two methods, what is the serialization, no What is the serialization, then you have told you, you can of course, you can call ObjectOutputStream.defaultWriteObject in these two methods.

() And ObjectInputStream.

DEFAULTREADOBJECT

() Still executing the default serialization (then do you use it on the code? Haha), you can also 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. Exterior, keywords like transient, violate, finally may not pay much attention, and now there are companies recruits to ask questions about asking such problems: (again, another solution is not to achieve serializable and change to implement Externalizable

interface. We study the source code of these two interfaces and found that they are very similar and easily confused. What we have to remember is: EXTERNALIZABLE does not save any object related information by default! Any actions for any saving and recovery objects are defined by yourself. Externalizables contains two public methods:

Public void writeexternal (ObjectOutput out) THROWS IOException; Public Void Readexternal (ObjectInput in) THROWS IOEXCEPTION, 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. There are a lot of topics about cloning, this is not fine here, if you are interested, you can refer to

IBM DeveloperWorks

An article:

Java pointer, reference and object's Clone

Little revelation

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

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