Java After class study questions (V)

Source: Internet
Author: User
Tags glob

1. Use files. Walkfiletree () Find all files with the. txt and. Java extensions under the specified folder.

Import java.io.IOException;
Import Java.nio.file.FileSystems;
Import Java.nio.file.FileVisitResult;
Import Java.nio.file.Files;
Import Java.nio.file.Path;
Import Java.nio.file.PathMatcher;
Import java.nio.file.Paths;
Import Java.nio.file.SimpleFileVisitor;
Import java.nio.file.attribute.BasicFileAttributes;

public class Fileglobnio {

public static void Main (String args[]) throws IOException {
String glob = "glob:**/*. {Java,txt} ";
String Path = "c:/";
Match (glob, path);
}

public static void Match (string glob, string location) throws IOException {

Final Pathmatcher pathmatcher = Filesystems.getdefault (). Getpathmatcher (Glob);

Files.walkfiletree (Paths.get (location), new simplefilevisitor<path> () {

            @Override
             public filevisitresult visitfile (path path,
                     basicfileattributes Attrs) throws IOException {
                 if (pathmatcher.matches (path)) {
                     System.out.println (path);
               }
                return Filevisitresult.continue;
           }

@Override
Public Filevisitresult visitfilefailed (Path file, IOException exc)
Throws IOException {
return filevisitresult.continue;
}
});
}

}

2. Use files. Walkfiletree () finds all files that are larger than the specified size (such as 1M) under the specified folder.

Import java.io.IOException;
Import Java.nio.file.FileSystems;
Import java.nio.file.FileVisitOption;
Import Java.nio.file.FileVisitResult;
Import Java.nio.file.FileVisitor;
Import Java.nio.file.Files;
Import Java.nio.file.Path;
Import Java.nio.file.PathMatcher;
Import java.nio.file.Paths;
Import java.nio.file.attribute.BasicFileAttributes;
Import Java.util.EnumSet;
public class Search implements Filevisitor {
Private final Pathmatcher Matcher;
Private final long accepted_size;
Public Search (String Glob,long accepted_size) {
Matcher= Filesystems.getdefault (). Getpathmatcher ("Glob:" +glob);
This.accepted_size=accepted_size;
}
void Search (Path file) throws IOException {
Long size = (long) files.getattribute (file, "Basic:size");
if (size ==accepted_size) {
System.out.println (file);
}
}
@Override
Public Filevisitresult postvisitdirectory (Object dir, IOException exc) throws IOException {
return filevisitresult.continue;
}
@Override
Public Filevisitresult previsitdirectory (Object dir, Basicfileattributes attrs) throws IOException {
return filevisitresult.continue;
}
@Override
Public Filevisitresult visitfile (Object file, Basicfileattributes attrs) throws IOException {
Search (Path file);
return filevisitresult.continue;
}
@Override
Public Filevisitresult visitfilefailed (Object file, IOException exc) throws IOException {
return filevisitresult.continue;
}
public static void Main (string[] args) throws ioexception{
String glob= "*.jpg";
Long size = 1048576;//1m=1024k=1048576 bytes
Path Filetree = Paths.get ("c:/");
Search Walk=new Search (glob, size);
Enumset Opts=enumset.of (filevisitoption.follow_links);
System.out.println ("C-disk size equal to 1M file has");
Files.walkfiletree (Filetree, opts, Integer.max_value, walk);
}
}

3. Use files. Walkfiletree () finds all TXT files that contain the specified string under the specified folder.

Import java.io.IOException;
Import java.io.*;
Import Java.nio.file.FileSystems;
Import Java.nio.file.FileVisitResult;
Import Java.nio.file.Files;
Import Java.nio.file.Path;
Import Java.nio.file.PathMatcher;
Import java.nio.file.Paths;
Import Java.nio.file.SimpleFileVisitor;
Import java.nio.file.attribute.BasicFileAttributes;

public class Fileglobnio {

public static void Main (String args[]) throws IOException {
String glob = "Glob:**/*.txt";
String Path = "c:/";
Match (glob, path);
}

public static void Match (string glob, string location) throws IOException {

Final Pathmatcher pathmatcher = Filesystems.getdefault (). Getpathmatcher (Glob);

Files.walkfiletree (Paths.get (location), new simplefilevisitor<path> () {

@Override
Public filevisitresult visitfile (path Path,
Basicfileattributes attrs) throws IOException {
if (pathmatcher.matches (path)) {
BufferedReader Reader =files.newbufferedreader (path);//Read the contents of the file
String Line=null;
while (line = Reader.readline ())!=null) {
if (line== "ASDFGHJKL")//if the Read content equals "ASDFGHJKL" then the output file name
{
SYSTEM.OUT.PRINTLN (path);
Break
}
}
}
return filevisitresult.continue;
}

@Override
Public Filevisitresult visitfilefailed (Path file, IOException exc)
Throws IOException {
return filevisitresult.continue;
}
});
}

}

4. Please understand this sample code by querying the JDK file and using a search engine, and figure out the relationships between watchable, Watchservice and other types, using UML class diagrams to represent the relationships between these classes.

The interface class for the java.nio.file.WatchService file System monitoring service, whose implementation is loaded by the monitoring service provider.

java.nio.file.Watchable implements the Java.nio.file.Watchable object to register the monitoring service Watchservice. java.nio.file.Pathimplements the watchable interface, and later uses the Path object to register the monitoring service.

Java.nio.file.WatchKey This class represents the registration relationship of the watchable object and the monitoring service Watchservice. Watchkey is created when the watchable object is registered with Watchservice. It is the association class between watchable and Watchservice.

To implement the file Change monitoring service step:

    1. Create an instance variable "Watcher" for Watchservice.
    2. Use Watcher to register each directory you want to monitor. When registering the directory to the monitoring service, you need to specify the type of event you want to receive file change notifications. The registered directory returns a Watchkey instance key.
    3. Perform an infinite loop to monitor the events to come. When an event occurs, the instance key is signaled and placed in the watcher queue.
    4. Get the key instance back from the watcher queue. The Key instance contains the name of the file where the change occurred.
    5. Get the suspended events from the key instance and process them as needed.
    6. Resets the key instance and restarts the monitoring event.
    7. Monitoring complete, turn off the monitoring service.

Class Diagram:

5. Write a program that specifies a folder that can automatically calculate its total capacity.

Import Java.io.File;
Import java.util.ArrayList;

public class Size {
static long size=0;
private static arraylist<string> filelist=new arraylist<string> ();
public static void Main (string[] args) {
Size s=new size ();
String filepath= "d:\\ software";
S.getfiles (FilePath);

}
To get all the directories and files under a certain path by recursion
void GetFiles (String filePath) {

File Root=new file (FilePath);
File[] Files=root.listfiles ();
for (File file:files) {
if (File.isdirectory ()) {
GetFiles (File.getabsolutepath ());
Filelist.add (File.getabsolutepath ());

}
else {
Size+=file.getabsolutepath (). Length ();
}
}
SYSTEM.OUT.PRINTLN ("size is" +size);


}

}

Java After class study questions (V)

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.