Java io--Plug-in

Source: Internet
Author: User
Tags serialization

Catalogue   1. File Class 2. InputStream and OutputStream 3. Reader and writer 4. Randomaccessfile 5. Serialization of Objects 6. Standard I/O 7. Process Control   content   1. File Class  The file class gives the feeling is the document class, actually to its appropriate interpretation is filepath (file path), the Java.io.File class can not only represent a specific file, but also can represent a set of file names under a directory. When file points to a set of files, it is possible to call the list () method on this collection to return an array of strings. Let's say we need to look at a list of directories and simply call list () if it's just a display, not a conditional choice, but most of what we need is a selective view, like looking at the current directory with more than one file that ends with ". Java". In this case, we need to use the directory filter. Packagecom.wetostudio.demo1801;

ImportJava.io.File;
ImportJava.io.FilenameFilter;
ImportJava.util.ArrayList;
ImportJava.util.Arrays;
ImportJava.util.List;
ImportJava.util.regex.Pattern;

Public classdirlist {
Public Static voidMain (string[] args) {
Used to display the current file path
System. out. println (System. GetProperty("User.dir"));

File Path = NewFile (".");
String[] list;
if(Args.length = = 0) {
List = Path.list ();
}
Else{
Callback
List = Path.list ( NewDirfilter (Args[0]));
}
Arrays. Sort(list,string. Case_insensitive_order);
for(String diritem:list) {
System. out. println (Diritem);
}
}
}
/**
* The reason for the existence of the Dirfilter class is to implement the Accept method, which provides the implementation to the list () invocation so that list () can callback the Accept (), which is often called a callback.
* Also an example of a strategic model (controversial), list implements the basic functionality and provides this strategy in the form of FilenameFilter to refine the algorithm that the list needs to provide the service.
* Because List accepts filenamefilter as a parameter, any object that implements the FilenameFilter class can choose how the list behaves. The policy mode provides the flexibility of the code.
*
* File list has been implemented to display the current path of the file name public string[] List () {...} and public string[] List (FilenameFilter filter) {...}
* However, it is necessary to implement the FilenameFilter interface when the file list is displayed with a custom processing.
* Public string[] List (FilenameFilter filter) {
* String names[] = list ();
* if ((names = = null) | | (filter = = null)) {
* Return names;
*      }
* List<string> v = new arraylist<> ();
* for (int i = 0; i < names.length; i++) {
* IF (filter.accept (this, names[i])) {//Call the Accept function in FilenameFilter
* V.add (names[i]);
*          }
*      }
* Return V.toarray (New String[v.size ())); *  } */

classDirfilter Implementsfilenamefilter{
PrivatePattern pattern;
PublicDirfilter (String regex) {
Pattern = pattern. Compile(regex);
}
@Override
Public BooleanAccept (File dir, String name) {
// TODOauto-generated Method Stub
return false;
returnPattern.matcher (name). matches ();
}

The test parameters are selected by themselves, and you can refer to the regular expressions above. Instead of just knowing how Java is implementing a way to display specific files in a particular directory, you are learning the implementation mechanism within Java. Here, thinking in Java is considered a strategy mode, while some books (such as "Crazy Java handouts") are considered command mode. Chapter 1: Strategy mode and Command mode     2. InputStream and OutputStream  Look at the level of InputStream and OutputStream below the java.io.* package (drawing is a waste of time). Figure 1.1 The concept of InputStream and outputstream hierarchical streams represents any data source object capable of producing data or is capable of receiving data-side objects. The concept of flow masks many of the details of processing data and facilitates the implementation of programming. Java io is divided into two parts: input and output. InputStream and reader-derived classes contain read (), which reads a single byte or byte array, and the classes derived from both OutputStream and writer contain write (), which is used to write a single byte or an array of bytes. But we don't usually use these methods, so to speak, they exist because other classes use them in order to provide a more useful interface. Therefore, we seldom use a single class to create a stream object, but rather by overlaying multiple objects to achieve some purpose, as can be seen in Figure 1.1, the FilterInputStream and Filteroutputstream classes are decorated with decorator design patterns. Figure 1.1 specific class details to see the JDK API. Chapter 2: Decorator design pattern The disadvantage of adorners: providing flexibility while simultaneously increasing the complexity of the code. Like the Java stream in this analysis, we have to create many classes-the "core" I/O type plus all the adorners to get the individual I/O objects we want.   3. Reader and writer  If InputStream and OutputStream are byte-oriented, then reader and writer are providing Unicode-and character-oriented I/O functionality. When we use I/O operations, most of them can be done in byte and character mode. For some text read and write is of course recommended to deal with the character, of course, can also be through the adapter class: InputStreamReader and OutputStream can convert InputStream to Reader,outputstream conversion to writer. But sometimes you have to ask for a byte-based flow, such as Java.util.zip, which is byte-oriented. The specific reader structure is directly on this side, such as 3.1 (figure does not go to the end, such as BufferedReader and sub-class LineNumberReader). Figure 3.1 Reader hierarchy graph writer 3.2. Figure 3.2 Writer's hierarchy diagram 4. Randomaccessfile  First, the Randomaccessfile class is an inheritance that does not belong to the above I/O, and it playing independently, directly inherits Java.lang.Object. The Randomaccessfile class operates on bytes. Randomaccess explained "arbitrary access" in Li Gang's words, randomaccessfile allowed to freely locate the file's record pointer ( file pointer ), you can start the I/O operation from where the file started. The randomaccessfile contains a record pointer that indicates the location of the current I/O operation, and when the program creates a Randomaccessfile object, the file record pointer is at the file header (0), and when n bytes are read/written, The record pointer of a file moves back n bytes. However, Randomaccessfile allows arbitrary movement of the record pointer. Long Getfilepointer (): Returns The current offset in this file. Offset: shift, void Seek (Long POS): Sets the File-pointer offset, measured from the beginning of this file, at which the N Ext Read or write occurs. The offset may set beyond the end of the file. Setting the offset beyond the end of the file does not the file length. The file length will change is writing after the offset have been set beyond the end of the file. Or en explained enough. Introduced so much, to tell you Unfortunately, most of Randomaccessfile's functions have been replaced by NIO methods.   5. Serialization of Objects   6. Standard I/O  The term standard I/O refers to the concept of "single flow of information used by programs" in Unix. All output from the program is from standard input, all of its output is sent to standard output, and all error messages are sent to the standard error. What it means: it's easy to put a program's output as input to another programs since it can be easily strung. Java provides system.in,system.out and System.err. System.out and System.err were packaged as PrintStream, but System.in was not packaged and unprocessed inputstream. This means that we can use System.out and system.err directly, but they must be packaged when reading system.in. We will use ReadLine () to read the input once, and for this we will wrap the system.in into BufferedReader to use this requirement we must use InputStreamReader to convert system.in into reader. As in the following example: Packagedemo1808;

ImportJava.io.BufferedReader;
ImportJava.io.IOException;
ImportJava.io.InputStreamReader;

Public classEcho {
Public Static voidMain (string[] args) throwsioexception{
BufferedReader br = NewBufferedReader ( NewInputStreamReader (System. inch));
String ReadLine = NULL;
while((ReadLine = Br.readline ())! = NULL&& readline.length ()! = 0) {//readline () can produce an exception
System. out. println (ReadLine);
}

}} compared to the system.in,system.out operation is much simpler, System.out is a printstream, and PrintStream is a outputstream,printstream has a can accept OutputStream as a parameter constructor, so only needs to invoke it to implement the System.out conversion PrintStream. Packagedemo1808;

ImportJava.io.PrintStream;

Public classChangesysout {
Public Static voidMain (string[] args) {
PrintStream PS = NewPrintStream (System. out, true);
Ps.print ("hello,changing System.out");
}} 6.1 Standard I/O redirectionThe Java system provides a number of static methods to allow redirection of standard input, output, and error IO streams. The IO redirection operation is a byte stream, not a character stream. 7. Process Control  Mainly through Java.lang.process,java.lang.processbuilder, etc. (skip)     Chapter 1:strategy mode and command mode   Strategy ModeApplication Scenario: CRM (Customer relationship System) for the sales department, to different customers to provide different quotations, this is a major complex problem, the different customers adopt different quotation algorithm. /** * Main completion for different users of the offer of different algorithms */ Public classPrice { Public DoubleQuoto ( DoubleGoodprice,string CustomerType) { if("Normalcustomer". Equals (CustomerType)) {System. out. println ("Normalcustomer Price:" +goodprice); returnGoodprice; } Else if("Teamcustomer". Equals (CustomerType)) {System. out. println ("Teamcustomer Price:" +goodprice*0.85); returngoodprice*0.85; } Else if("Largecustomer". Equals (CustomerType)) {System. out. println ("Largecustomer Price:" +goodprice*0.8); returngoodprice*0.8; }//other Customer returnGoodprice; }} above the design produces the following two questions:
    • The price class contains all the algorithms, the structure is huge, difficult to maintain
Then there may be such a design, as follows Public classPrice { Public DoubleQuoto ( DoubleGoodprice,string CustomerType) { if("Normalcustomer". Equals (CustomerType)) { return This. Calupricenormalcustomer (Goodprice); } Else if("Teamcustomer". Equals (CustomerType)) { return This. Calupriceteamcustomer (Goodprice); } Else if("Largecustomer". Equals (CustomerType)) { return This. Calupricelargecustomer (Goodprice); }//other Customer returnGoodprice; } Private DoubleCalupricelargecustomer ( DoubleGoodprice) {...} Private DoubleCalupriceteamcustomer ( DoubleGoodprice) {...} Private DoubleCalupricenormalcustomer ( DoubleGoodprice) {...}} Feel good, maintenance on the relatively simple point, only need to modify the specific method is OK. is that really it? --If more customer types are present, the price category will still be bloated.  
    • Poor scalability, in the face of increased number of types of customers
For example, to add more customer types, there is the user type unchanged, the addition of other factors, such as the concept of adding time, on holidays (51, 11, etc.) to the user to take a different price algorithm. Analysis of the above problems: various calculation of the price of the way is like a specific algorithm, using these calculations to calculate the price of the program, is equivalent to the use of the algorithm of the customer. The root cause of the problem with the design above is that the algorithm and the customer using the algorithm are coupled. Solution: The policy pattern defines a series of algorithms, encapsulates them, and allows them to replace each other. The pattern allows the algorithm to change independently of the customers who use it. Through the strategy model to solve the above problem, should be all the price calculation method independent, each calculation method is implemented by a single class, a series of algorithm classes to define a common interface, the implementation of the algorithm is the different implementation of this interface, status is equal, can be converted to each other. In this way, a new algorithm is added to add an algorithm implementation class, to maintain an algorithm, but also just modify the implementation of an algorithm, to solve the scalability, maintainability. In order to make the algorithm independent of the client using it, the policy mode introduces a context object, which is responsible for holding the algorithm, but is not responsible for deciding which algorithm to use, he gives the selected function to the customer, has the customer chooses the concrete algorithm, sets to the context object, lets the context object hold the customer chooses the algorithm, The context object invokes the specific algorithm when the client notifies the context object to perform the function. This enables the separation of the algorithm from the customer. The following is a redesign of the original issue through the policy model. Design class diagram as shown in the price class is a context class, through price just hold the Pricestrategy interface algorithm, the client is the decision to choose the specific algorithm class. section of the code is shown below. PackageStrategy.domo;

Public class Client{

private static Double goodsprice = 1000;

Public Static voidMain (string[] args) {
Pricestrategy LPs = NewLargepricestrategy ();
DoubleGoodsprice = 1000;
Price = NewPrice (LPS);

System. out. println (Price.caluprice (Goodsprice));

}} PackageStrategy.domo;

Public class Price{

PrivatePricestrategy PS = NULL;

PublicPrice (Pricestrategy PS) {
This. PS = PS;
}

Public DoubleCaluprice ( DoubleGoodsprice) {
returnPs.pricestrategyinterface (Goodsprice);
}} PackageStrategy.domo;

Public Interface Pricestrategy{
Public DoublePricestrategyinterface ( DoubleGoodsprice);} PackageStrategy.domo;

Public class Normalpricestrategy ImplementsPricestrategy {

Public DoublePricestrategyinterface ( DoubleGoodsprice) {
// TODOauto-generated Method Stub
System. out. println ("Ordinary user");
returngoodsprice*1;
}

}//omitting Teampricestrategy and Largepricestrategy implementations ... The function of the strategy mode is to separate the specific algorithms from the specific business processes and implement them into separate classes. The focus of the strategy pattern is not how to implement the algorithm itself, but how to organize, call these algorithms, so that the program has a good maintainability and extensibility. If-elseif statement Ability is an equal function structure, and the strategy mode is the coordination call equality Strategy algorithm implementation, at this point is interlinked, so in the encounter If-elseif statement can refer to the design of the policy mode. There are two ways to choose the strategy in the strategy mode, one is to select the specific strategy algorithm by client, and then throw the process of executing the algorithm to the context (Priice in the above example), and the other is the client regardless of the context to decide which algorithm to execute. For example, fault-tolerant recovery (refer to "Software Engineering", "design mode", "policy Mode"). Command Mode               Chapter 2: Decorator design pattern  Exercise 1: Design a program that operates in a set of files that can be either local or spread across the entire directory tree, displaying the folders under the current file, and the list of files, which can traverse the entire directory tree. For example environment:->dirhome-->java ——— >jdk ——— >document.doc-->spring ——— >spring.zip ——— >springapi ———— > Document.doc-->pass.txt output:./java./java/jdk./java/document.doc./spring./spring/springapi./spring/springAPI/d Ocument.doc./spring/spring.zip./pass.txt add Condition: Show specific folders and files (policy mode design) Exercise 2: Redirect input and output, convert file In.txt files to OUT.txt Exercise 3: Write the Readprocess.java class and then command Run "Javac Readprocess.java" to print the display information to a local OUT.txt Exercise 4: Implement the ability to insert content into a specified file, at a specified location, Complement method public static void Insert (String filename,long pos,string insertcontent) throws ioexception{...} writing test Cases Insertconten T.java class to Be continued

Java io--Plug-in

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.