Java input and Output (ii)--specific operation

Source: Internet
Author: User
Tags object serialization

Text input and output

The class for text output is PrintWriter, which provides the ability to format output characters, which is a subclass of writer. Similar to the use of System.out, PrintWriter instances provide a lot of similar output functionality. System.out is an instance of PrintStream, PrintStream is a subclass of OutputStream, so System.out and PrintWriter instances are in the same position and therefore have similar operations. The difference is that the System.out is responsible for the byte stream output, while the PrintWriter is responsible for character stream output.

The destination of the PrintWriter output can be anywhere, depending largely on what the output stream is bound to printwriter.

Output to file using PrintWriter:

PrintWriter out=new PrintWriter (New FileWriter ("file.txt"));

Using PrintWriter output to standard output (screen):

PrintWriter out=new PrintWriter (System.out);

PrintWriter has a constructor that takes a OutputStream object as a parameter

In addition, the combination of stream filters can be used to implement other functions, such as adding bufferdwriter to join the cache mechanism.

There are many implementations of the read-in feature of text, such as the use of scanner instances to bind system.in for reading of standard inputs. Use BufferedReader to bind a file for reading:

BufferedReader br=new BufferedReader (New InputStreamReader (New FileInputStream ("file.txt"));

Similarly, scanner can also read the file, BufferedReader can also read the standard input, the implementation of these features mainly take advantage of the function of the stream filter, the difference is that scanner can read the number, BufferedReader can only read the string.

binary input and output

The classes responsible for writing the read binary are mainly DataInputStream and DataOutputStream. These two classes implement the Datainput and DataOutput interfaces respectively. Direct read and write binary reads and writes the Java basic data type directly. Write is to directly convert the data into binary form to save, read is the reverse operation. For example, to save the number 1234, the text write is to write it into 4 characters, while the binary directly writes the binary form of the number 1234. This is faster and more efficient relative to text processing.

Object Flow and serialization

The Java language supports a very general mechanism called object serialization, which can write out any object into a stream and read it back later. This mechanism is particularly suitable for applications that transfer objects in a distributed environment. To implement an operation where an object can be serialized, the class to which the object belongs needs to implement the serialization interface, the Serializable interface, which has no methods. This is similar to the Cloneable interface, but in order to implement cloning, you need to overwrite the Clone method in the object class in the class.

To implement the input and output of the object flow, you need to use the ObjectInputStream class and the ObjectOutputStream class. Here's how to use it:

ObjectOutputStream out=new ObjectOutputStream (New FileOutputStream ("Employee.data"));

Employee Harry=new employee ();

Manager boss=new Manager ();

Out.write (Harry);

Out.write (boss);

When you need to restore an object, use the ObjectInputStream class using the following method:

ObjectInputStream in=new ObjectInputStream (New Fileinputsream ("Employee.data"));

Employee e1= (Employee) In.readobject ();

Employee e2= (Employee) In.readobject ();

In the case of serializing an object, there is a case where multiple objects refer to the same object, when the serialization technique saves the object more than once, instead of saving the same object multiple times, it uses a number called the serial number to point to the same object, and the same object is saved only once.

Manipulating files

In Java file I/O, in addition to stream processing, there is also the processing of files and directories, that is, the operation of the disk files. In versions prior to Java 7, the file class was provided to handle these operations. After Java 7, the path and files classes are provided to manipulate the file. Path represents the directory structure of a file or directory. Files provides a number of ways to manipulate the file, such as moving deleted copies of files. Files also provide the ability to manipulate the contents of the file directly, similar to

Files.newinputstream (path);

Files.newoutputstream (path);

Files.newbufferedreader (Path,charset);

Files.newbufferedwriter (Path,charset);

These actions can prevent the user from getting bogged down in handling various stream processing scenarios. In addition, the files provide a way to iterate through the file in the directory, Walkfiletree, to pass an object of type Filevisitor to it when using this method. The methods in this object can be called when a particular situation is encountered.

Memory-Mapped files

Most operating systems can use virtual memory technology to map a file or part of a file into memory, so that the file can be accessed as an array in memory, speeding up the speed of file access.

Java provides an abstract class buffer for memory mapping with a file. Specific Bytebuffer,charbuffer and other classes can be used in practice. To use the memory-mapping mechanism, you need to use the FileChannel class to open a channel (channel), which is an abstraction of the disk file, with access to operating system features such as memory mapping, file locking mechanisms, and fast data transfer between files, which require operating system support.

How to use memory maps:

FileChannel Channel=filechannel.open (path,options);

Mappedbytebuffer buffer =channel.map (filechannel.mapmode.read_only,0,length);

Regular expressions

A regular expression is a mechanism for handling strings that can be matched to a string by describing a pattern. The regular expressions are not described in detail here, which mainly describes the use of the normal expressions in Java:

Pattern pattern=pattern.compile (pattern);

Matcher matcher=pattern.matcher (input);

Matcher.matchs () Returns true to indicate that the input string matches the required pattern, and Matcher.find () returns true to indicate that there are substrings in the input string that satisfy the pattern match. Where input can be an object of any class that implements the Charsequence interface, such as String,stringbuilder,charbuffer.

The Matcher class provides the start and end methods used to return the position of the matched substring in the input string. Similar to the use of iterators, you need to use the Find () method once to get the next matching substring using these two methods.

Java input and Output (ii)--specific operation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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