Java cafe (9)-a compressed archiving utility

Source: Internet
Author: User

Excellent creativity creates practical tools. With the help of powerful built-in APIs in Java, even beginners of Java, as long as they are good at dispatching, can also become the overlord of the world! Faster first

In the age of virus and BT download, it is a good habit to back up on time. Generally, only software that meets the following arrogant needs can be called a handy tool:

★Files to be backed up may be distributed in all corners of the hard disk;
★The file name may be complex and cannot be clearly described using the DOS wildcard;
★Filter files by time, size, type (file or directory), and last modification time;
★The ability to compress these files and add appropriate comments to help identify them;
★You can add a verification value to ensure that no error occurs during replication and network transmission;
★Maintain the directory structure during Backup for recovery;
★It is best to be able to run on multiple platforms at the same time;

Does such software exist? That's right. This is the theme of our cafe. We will use all the knowledge we have learned to compile an ExpZip utility.

First, we will introduce how to use the software. Java cafe is still a command line tool because it has only a few issues since it was opened and has not introduced the GUI (graphical user interface) design. For example, for Java enthusiasts, it is even more important to write their own programs. This is a painstaking effort of N hours. Naturally, it should be backed up frequently, and there is no regret in the world. Open the "command prompt" window, enter the project folder, and enter:

java ExpZip "C:Documents and SettingsGary Chanworkspace" "[a-zA-Z_$][w$]*.java"

Java is the Java interpreter, and ExpZip is the class file after the Java class is compiled. The first parameter represents the target folder, and the second parameter represents the expression of the target file name. For more information, see the following description. After returning, all Java source programs included in all subfolders in the eclipseworkarea folder have been forwarded to backup.zip. You can use WinRAR to open the ZIP package.

It can be seen that this compressed package retains the file path information, and there are annotations, recording the compression information at that time. Moreover, this is a Java program. Theoretically, it is okay to run it on MacOS.

In short, this is a very powerful software, and we already have enough knowledge to write this software. Create a new project first.

Java File Operations

  1. File class

In Java, files and paths are accessed through the File class. Yes, this is a very confusing name. You may think it can only process files. In fact, it can represent a specific file and a list of file names in a folder. If it is a file, you can get its size through the length () method, the last modification time through the lastModified () method, and so on; if it represents a list of file names, you can use list () obtain the string array that represents the File name list, or use the listFiles () method to obtain the File array that represents the sub-File list. In short, folders and files in Java have been unified into an abstract concept. It is very convenient to use as long as you understand its principles.

  2. File Filtering

As we have said, the listFiles () method of the File class can get the File array representing the sub-File list. If you only want to get a specific sub-File and filter out other files, you can add the parameter-a filter to the listFiles () method.
The so-called filter is a Java class that implements the FilenameFilter interface. The so-called interface only defines the behavior protocol. All classes declared to implement this interface must implement the behavior of this interface. In other words, an interface is a contract. For example, the definition of FilenameFilter is as follows:

public interface FilenameFilter {
boolean accept(File dir, String name);
}

We want to get all subfolders of a File class. The filter FolderFilter class can be written as follows:

class FolderFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return new File(dir + "\" + name).isDirectory();
}
}

As you can see, the FolderFilter class supports the FilenameFilter interface through implements, and then implements the accept method of this interface. Specifically, in the accept method, create a File instance using the input dir and name parameters, and call the isDirectory () method to determine whether the instance is a folder. If yes, True is returned, otherwise, False is returned.

Note that this method must be exactly the same as that declared in the FilenameFilter interface. Because of this, it is both troublesome and error-prone to manually enter the interface declaration each time. Let Eclipse do it! Open Eclipse and create a new class named FolderFilter. Click Add on the right of the Interfaces text list and enter FilenameFilter in the pop-up dialog box. In fact, Eclipse will filter based on your input, which is very smart (see figure 1 ).


Do not forget to tick Inherited abstract methods only. Finally, press Finish to create the FolderFilter. Complete the code according to the above.

Assuming that path is an instance of the File class, we can use File [] subFolders = path. listFiles (new FolderFilter () to get the list of subFolders of path.

This is the use of the interface. With the knowledge of encapsulation, inheritance, and polymorphism in the Java language we explained the previous two times, Java object-oriented programming is basically finished.

  3. Filter Principle

You may think it is too troublesome to manually write a class to filter folders. Actually, it is not.
The listFiles () parameter is provided with an instance of a class that implements the FilenameFilter interface. The only purpose is to allow listFiles () to call the accept method of the parameter instance in turn. It is meaningful to have a thorough understanding of this tongue twister. This means that you can pass any instance of the class implementing the FilenameFilter interface as a parameter, or even dynamically change it at runtime, making the program more flexible. Moreover, if you want to add more filters, you can write additional classes without modifying the original filters. The idea of this dynamic Strategy is a reflection of a Strategy model.

Sugar

  Design Patterns)

Cristopher Alexander, a building engineer, summed up the lessons learned in the building and found that some problems always repeat over and over again. When you come up with a set of core solutions to this problem, you just need to use this solution without having to worry about other solutions. Although this sentence is simple, it has become a very important methodology in software engineering-the guiding ideology of the design model.

We know that the architecture has Newton mechanics as a dialectical theoretical basis, as long as we respect science, it is impossible to design a collapsed building (even if it collapsed, it is caused by material construction failure or other factors ). However, writing software does not have such a theoretical basis, because the program only tells the computer syntax that the computer only needs to do so according to the plan, there is no mechanism to ensure that the semantics of the program conforms to human thoughts. Therefore, the program will have bugs, even if Bill yelled at Windows XP: "I'm not sure you have bugs in the name of my ancestors !", Can Windows XP understand the spirit?

Although there is no complete solution, four masters of computer scientists, including Erich Gamma, created a design model in the software by drawing on the concept of the model in the architecture. Through the 23 models carefully extracted, it effectively solves Software Design Problems and adds a certain degree of model semantics to the program. For details, please read the Design Patterns book written by Gang of Four. It is worth mentioning that the name parser we wrote last time uses the Factory mode, and the structure is very beautiful.

By the way, there are more and more tools to support design patterns. If you want to upgrade from a Java programmer to a sound Java architect one day, this is a required course!

  4. Regular Expression (Regular Expression)

When talking about regular expressions, you may feel familiar with them even if you are not familiar with them. No, the current text editing software, whether UltraEdit or EditPlus, supports regular expressions. It can be said that the editor that does not support regular expressions is definitely a three-stream product.

In theory, regular expressions are equivalent to finite automatic machines and can express a wide range of languages. In DOS, wildcards cannot be considered. Those who have learned compilation principles or computer theory must be familiar with it. However, if I start from the beginning, I am afraid that all the la s in this issue are insufficient. Therefore, we recommend that you refer to the Regular Expressions chapter in Sun's free Java Tutorial, which is detailed. Even if you are familiar with regular expressions in computer theory, you are advised to take a look, because Java adopts Perl-like syntax, which is somewhat different from that in theory books.

For example, we need to filter out all Java source programs. As we all know, a Java file name must start with a letter, dollar sign, or underline, and can be any combination of digits, letters, dollar signs, or underscores. The last extension is java. The regular expression is "[a-zA-Z _ $] [a-zA-Z _ $0-9] *. java" (without quotation marks ).

[A-zA-Z _ $] indicates lowercase letters a to z, uppercase letters A to Z, dollar signs or underscores; [a-zA-Z _ $0-9] * represents any of the ten numbers lowercase letters a to z, uppercase letters A to Z, dollar signs, underscores, and 0 to 9 combination; ". java "indicates the extension of the Java source program. "It has special significance in Java regular expressions, so". "indicates a". "symbol.

Of course, there are many extensions in the Java Regular Expression API, which can be abbreviated as [a-zA-Z _ $] [w $] *. java.

With this knowledge, it is not difficult to write a file filter FileFilter that supports regular expressions. The source code is as follows:

public class FileFilter implements FilenameFilter {
private Pattern pattern;

public FileFilter(String regex) {
pattern = Pattern.compile(regex);
}

public boolean accept(File dir, String name) {
File file = new File(dir + "\" + name);
return pattern.matcher(file.getName()).matches() && file.isFile();
}

}

In Java, regular expressions are used through the Pattern class. In the FileFilter constructor, pass the regex parameter to the compi of Pattern.

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.