1 File class
File
The name of the (document) class is somewhat misleading; we may think that it refers to a document, but it is not. It can represent both the name of a particular file and the name of a group of files under a directory. In fact FilePath
, the ( file path ) is a better name for this class.
If it refers to a set of files, we can call list()
The method on this collection, which returns an array of strings.
2 inputs and outputs (input an output)
The I/O class Library of a programming language often uses the abstract concept of flow , which represents any data source object capable of producing data or a receiving object capable of receiving data . The stream masks the details of the processing data in the actual I/O device.
We seldom use a single class to create a flow object, but rather by overlapping multiple objects to provide the desired functionality (this is the adorner design pattern). In fact, the main reason for confusing the "stream" class library in Java is that creating a single result stream requires creating multiple objects.
In Java 1.0, the designer of a class library first qualifies all classes related to input to inherit from InputStream
, and all classes related to the output should inherit from OutputStream
it.
Read () in InputStream or reader is used for reading a single byte or byte array , and OutputStream or writer is used to write a single byte or byte array.
2.1 InputStream Type
InputStream
is used to represent classes that produce input data from different data sources . Each data source has a corresponding InputStream subclass . These data sources include:
A byte array. An array of bbytes.
A string object. A String object.
File. A file.
"Pipe" (A pipe), working in A similar way to the actual pipe, i.e., input from one end and output from the other end.
A sequence of other kinds of streams so that we can merge them into one stream. A sequence of other streams.
Other data sources, such as Internet connectivity. Other sources.
2.2 OutputStream Type
OutputStream
The class determines the target to which the output is going:
3 adding properties and useful interfaces
FilterInputStream
And FilterOutputStream
is the two classes used to provide the adorner class interface to control a specific input stream (inputstream) and output stream (OutputStream), whose names are not intuitive. These two classes are necessary for adorners (so that they can provide a common interface for all objects being decorated).
4 Reader and Writer
Design Reader
and Writer
inheritance hierarchies are primarily for internationalization . The old I/O stream inheritance hierarchy supports only 8
bit-byte streams and does not work well with 16
Unicode characters for bits . Because Unicode is used for character internationalization (char in Java itself is also 16-bit Unicode), the Reader
Writer
hierarchy is added and inherited to support Unicode
all I/O operations . In addition, the new class library is designed so that it operates faster than the old class library.
5 self-contained classes: Randomaccessfile
RandomAccessFile
Applies to files made up of known-sized records, so we can use to move seek()
records from one place to another and then read or modify records.
RandomAccessFile
Have behavior that differs fundamentally from other I/O types because we can move forward and backward within a file. In any case, it is self-contained and derives directly from object.
Essentially, Randomaccessfile works like a combination of DataInputStream and dataoutputstream, and adds some new methods:
getFilePointer()
To find the location of the file that is currently located,
seek()
To move to a new location within a file,
length()
Used to determine the maximum size of a file.
6 Typical use of I/O streams (typical uses of I/O streams)
Although I/O stream classes can be combined in different ways, we may be using only a few of these combinations. The following example can be used as a basic reference for typical I/O usage.
6.1 Buffered input files (Buffered input file)
6.2 Input from memory
6.3 Formatted memory input (formatted. Input)
6.4 Basic file outputs (basic document output)
6.5 Storing and recovering data (storing and recovering)
6.6 Read-Write random Access file (Reading and writing random-access files)
6.7 Pipe Flow (pipedstreams)
7 Standard I/O (I/O)
The term standard I/O refers to the concept of " single flow of information used by programs " in Unix.
The meaning of standard I/O is that we can easily concatenate programs together, and the standard output of one program can be the standard input for another program.
8 New I/O
The increase in speed comes from the way in which the structure used is closer to how the operating system performs I/O: channels and buffers . We can think of it as a coal mine, the channel is a mineral that contains coal (data), and the buffer is a truck that is sent to the mine. The truck was full of coal and we got coal from the truck. That is, we do not have direct interaction with the channel, we just interact with the buffer and dispatch the buffer to the channel. The channel either obtains data from the buffer or sends data to the buffer.
The only buffer that interacts directly with the ByteBuffer
channel is--that is, buffers that can store unprocessed bytes. When we query the JDK document java.nio.ByteBuffer
, we find that it is a fairly basic class: Create an object by telling how much storage space is allocated, ByteBuffer
and there is also a method selection set for outputting and reading data in the original byte form or base data type. However, there is no way to output or read an object, even if it is a string object. This is a very low-level process, but it happens because it is a more efficient way to map most operating systems.
8.1 Channel FileChannel
FileChannel
is to manipulate the byte stream . There are three classes in the old I/O class library that have been modified to produce FileChannel
:
Fileinputstream.getchannel ()
Fileoutputsteam.getchannel ()
Randomaccessfile.getchannel ()
Package Net.mrliuli.io.nio;import java.nio.*;import java.nio.channels.*;import java.io.*;p ublic class GetChannel {pri vate static final int bsize = 1024; public static void Main (string[] args) throws Exception {//Write a File:filechannel fc = new FILEOUTPUTST Ream ("Data.txt"). Getchannel (); Fc.write (Bytebuffer.wrap ("Some text". GetBytes ())); /* Bytebuffer buffer = bytebuffer.allocate (1024); Fc.read (buffer); Nonreadablechannelexception System.out.println ((char) buffer.get ()); */Fc.close (); Add to the end of the FILE:FC = new Randomaccessfile ("Data.txt", "RW"). Getchannel (); Readable and writable Fc.position (Fc.size ()); Move to the End Fc.write (Bytebuffer.wrap ("some more". GetBytes ())); Fc.close (); Read the FILE:FC = new FileInputStream ("Data.txt"). Getchannel (); Bytebuffer buff = Bytebuffer.Allocate (bsize); Fc.read (Buff); Fc.write (Bytebuffer.wrap ("Again". GetBytes ())); Nonwritablechannelexception Buff.flip (); while (Buff.hasremaining ()) System.out.print ((char) buff.get ()); Bytebuffer.get () returns a byte System.out.println (); }}
8.2 Buffer Bytebuffer
How to store bytes in the buffer bytebuffer:
Using put()
a direct fill, fill in one or more bytes, or a value of the base data type;
Use wrap()
to wrap an existing byte array into Bytebuffer.
8.3 read (), write (), flip (), Write ()
Features an input channel in
, an output channel, out
and a buffer buffer
:
-
in.read (buffer);
will FC Byte input buffer
in
, at which point the Buffer.flip () must be adjusted again;
Be prepared to let others read bytes from buffer
.
-
out.write (buffer)
outputs bytes in buffer
to After the out
, write ()
operation, the information is still in the buffer buffer
and must be called buffer.clear ( );
Reschedule all internal pointers so that the buffer is ready to accept data during another read ()
operation.
Package Net.mrliuli.io.nio;import java.io.*;import java.nio.*;import java.nio.channels.*;p ublic class ChannelCopy {PR ivate static final int bsize = 1024; public static void Main (string[] args) throws Exception {if (args.length! = 2) {System.out.println ("Argu Ments:sourcefile destfile "); System.exit (1); }//Open a Filechaanel for reading (input) FileChannel in = new FileInputStream (Args[0]). Getchannel (); Open a FileChannel for write (output) FileChannel out = new FileOutputStream (args[1]). Getchannel (); A buffer that allocates bsize bytes Bytebuffer buffer = bytebuffer.allocate (bsize); /* * Return the number of bytes read, possibly zero, or <tt>-1</tt> if the channel has reached end-of- Stream * Filechanel.read () * *//-11 delimiters (originating from UNIX and C), indicating the end of the input while (in.read (buffer)! =-1 {Buffer.flip ();//Prepare for writing out.write (buffer); After the write () operation, the information is still buffered, the clear () operation is rescheduled for all internal pointers so that the buffer is ready to accept data during another read () operation. Buffer.clear (); Prepare for Reading}}}
8.4 Converting data
Buffers contain normal bytes, and in order to convert them into characters, we either encode them when they are entered (so that they will be meaningful when they are output) or decode them when they are output from the buffer. You can java.nio.charset.Charset
use classes to implement these features, which provide a tool that encodes data into a number of different types of character sets. The buffer contains plain bytes, and to turn these into characters, we must either encode them as we put them in (So, they would be meaningful when they come out) or decode them as they come out of the buffer. This can is accomplished using the Java.nio.charset.Charset class, which provides tools for encoding into many different t Ypes of character Set.
8.5 View Buffers
The view buffer allows us to view the underlying bytebuffer of a particular basic data type. Bytebuffer is still the place where the data is actually stored and "supports" the previous view, so any changes to the views are mapped to changes to the data in the Bytebuffer.
8.6 File plus Lock
File locking is visible to other operating system processes because the Java file lock directly maps to the lock tool on the local operating system.
Exclusive Lock Exclusive lock
Locking portions of a mapped file to lock part of the mapping files
Cretical Section critical area
9 Compression (Compression)
10 serialization of objects (object serialization)
The Java object serialization converts the objects that implement Serilizable
the interface into a sequence of bytes , and is able to restore the sequence of bytes to the original object at a later time. This process can even be passed through the Internet court This means that the serialization mechanism can automatically compensate for differences between different operating systems.
In itself, the serialization of objects is interesting because it allows for lightweight persistence (ligthweight persistence). persistence means that the lifetime of an object does not depend on whether or not the program is executing, it can exist between calls to the program.
The concept of object serialization is added to the language to support two main features:
One is the remote method invocation of Java (Invocation, RMI), which makes objects that exist on other computers as if they were native. When sending a message to a remote object, it is necessary to transfer the parameters and return values through object serialization.
Furthermore, for Java beans, the serialization of objects is also required. When using a bean, it is typically configured at design time for its state information. This state information must be saved and later restored at the start of the program, which is done by the object serialization.
serialize an object and deserialize:
The first thing to do is to create an ObjectOutputStream
object that contains an object through a constructor OutputStream
.
Then, simply call void writeObject(Object obj)
, the object can be obj
serialized, that is, converted into a sequence of bytes output to the first step of the said Outputstream
.
Deserialization, the byte sequence is restored to an object, then only the call ObjectInputStream
Object readObject()
, input into one InputStream
.
Cases:
Worm.java
10.1 Find Class
When reverting a sequence of bytes to an object, the Java Virtual machine must be guaranteed to find the relevant .class
file for the object to be restored , or throw an java.lang.ClassNotFoundException
exception.
10.2 Serialization Control
You can use Externalizable
an interface if you want only some information for an object to serialize and some information is not serialized, that is, serialization control .
10.2.1 Externalizable Interface
Externalizable
interface inherits from Serializable
the interface, there are two methods as follows, both of which are called automatically during serialization and deserialization.
void writeExternal(ObjectOutput obj)
, only the required portions are explicitly serialized within the method.
void readExternal(ObjectInput in)
10.2.2 Externalizable interface differs from Serializable interface
Externalizable
Serializes only writeExternal()
the parts, and Serializable
automatically serializes them all.
Externalizable
At deserialization time (that is readObject()
, when called), all normal default constructors are called first and then called readExternal()
.
Serializable
When deserializing, the object is constructed entirely on the basis of the bits it stores, without invoking the constructor .
Cases:
Blips.javaBlip3.java
10.2.3 transient
(instantaneous) keywords
If we are working on a serializable object, all the serialization operations will be done automatically. To be able to control it, transient
You can use the (instantaneous) keyword to turn off serialization by field, which means "do not bother you to save or recover data-I will handle it myself".
Because Externalizable
objects do not save any fields by default, transient
keywords can only be used with Serializable
objects.
10.3 Serialization Persistence
We can use object serialization through a byte array to achieve deep copy of any serializable object-deep copy means we replicate the entire object net, not just the base object and its references.
When an object is serialized in a single stream, it can be restored to the same object net as we wrote it, and there are no accidentally duplicated objects.
An object is serialized in a different stream and then recovered from a different stream, resulting in a different object address.
Cases:
Myworld.java
An important limitation of object serialization is that it is just a Java solution: Only Java programs can deserialize such objects. A more interoperable solution is to convert data into XML format, which can be used in a variety of platform languages.
Related articles:
Java programming thought Lesson (iii) 15th-generics
java Programming thought Lesson (iv) 17th-container in-depth discussion