java_05_IO

java_05_IO

1, hands-on brain

Use Files. WalkFileTree () to find the specified folder and all larger than the specified size (such as 1M) file.

analysis of idea:

1) Find all files in that folder.

2) find out the number of bytes is greater than 1 * 1024 * 1024 and outputted.

package com.me.afterclass;

import java.io.File;

public class Size {
    public static void main(String[] args) {
        File dir = new File("D:\\java编译器");
        File[] files=dir.listFiles(); 
         for(int i=0;i<files.length;i++)  
            {
             if(files[i].isFile())  
                 {
                 if(files[i].length()>1*1024*1024)
                     System.out.print(files[i]+"的大小:");
                     System.out.printf("%.2f",files[i].length()/1024.0/1024.0); 
                     System.out.println("M");
                 }
            }
    }

}

Run tests:

Use Files. WalkFileTree () to find all files with the extension .txt and .java specified folder.

Source:

package com.me.afterclass;


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 houzhui {

    public static void main(String args[]) throws IOException {
        String glob = "glob:**/*.{java,txt}";
        String path = "D:\\JAVA\\源代码\\java上课";
        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;
            }
        });
    }

}

Run tests:

Use Files. WalkFileTree () to find all inclusive specified string txt files in the specified folder.

analysis of idea:

1, to find out the suffix .txt files.

2, line by line and then find out if there is a corresponding character.

Source:

package com.me.afterclass;

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 Content {

    public static void main(String args[]) throws IOException {
        String glob = "glob:**/*.txt";
        String path = "D:\\JAVA\\源代码\\java上课";
        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)) { 
                 the BufferedReader Reader = Files.newBufferedReader (path); // contents of the document reading 
                  String Line = null ;
                   the while (! (= reader.readLine Line ()) = null ) {
                    IF ( line.indexOf ( "main") = -! 1) // If the content is equal to read "main" output file name
                        // int indexOf (string string) returns the first occurrence of the substring in this string in the index. Not found returns -1 
                   { 
                         System.out.println (path); 
                         BREAK ; 
                   } 
                  } 
                } 
                  return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc)
                    throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
    }

}

Run tests:

 

 

 Second, the hands-on brain: Implement monitoring folder feature

Watchable Path class implements an interface, so we can monitor its changes. FileWatchDemo.java example shows how to monitor the new files in a folder, delete and rename. Please JDK file by querying a search engine and use, etc., this sample code to read and understand the relationship between Watchable, WatchService other types, using UML class diagram shows the relationship between these classes.

WatchService 
seen as a file monitor, to run through the operating system native file system. 
For the case of single points of appkey, you can register open multiple monitors. 
Each monitor can be seen as a background thread to achieve monitored by signal monitoring document issued.

WatchService been registered to observe objects all the changes and events

Watchable is observer, in combination with WatchService, java.nio.file.Path been achieved 

WatchService instantiation: 

WatchService watchService = FileSystems.getDefault().newWatchService(); 

Examples of use of the monitored object Path Watchable 

Path dir = Paths.get(path); 

The Path to register WatchService // create here in the monitoring file, modify, delete, but the key here to return inside the monitoring information is empty 

WatchKey key = dir.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);   

Note: Monitor pool is static, only when you take the initiative to get a new pool will be monitoring the updated content added to monitor the pool. This creates a problem monitoring system receives information about the event may be slightly longer. 

1, java.nio.file.WatchService file system monitoring services interface class, and its concrete realization of the responsibility of monitoring the service provider loaded. 

2, ava.nio.file.Watchable in order to achieve the target of java.nio.file.Watchable the registered monitoring service WatchService. java.nio.file.Path realized watchable interface later use Path object registration monitoring service. 

 3, java.nio.file.WatchKey class represents a registered relationship Watchable objects and monitoring services of WatchService. WatchKey is created when Watchable WatchService subject to registration. It is an association between the class and the Watchable WatchService.

Third, homework:

1, write a program that specifies a folder, which can automatically calculate the total volume;

Analysis of ideas:

1), the file will be stored in the specified folder list.

2), if the subdirectory, wherein the file is added to the list.

3) calculate the size of all files and outputs.

package com.me.afterclass;

import java.io.File;
import java.util.ArrayList;
public class Capacity {
    static long size=0;
    private static ArrayList<String> filelist=new ArrayList<String>();
    public void getFiles(String filePath)
    {
        File root=new File(filePath);
        File[] files=root.listFiles();
        for(File file:files)
        {
            if(file.isDirectory())//If subdirectory in which the file is added to the list 
            { 
                getFiles (file.getAbsolutePath ()); 
                filelist.add (file.getAbsolutePath ()); 
            } 
            the else  
            { 
                size + = file.getAbsolutePath () length ().; 
            } 
        } 
        of System.out.print ( "D: \\ \\ the JAVA source code \\ java class total capacity:" ); 
        System.out.println (size + "bytes" ); 
    } 
    public  static  void main ( String [] args) 
    { 
        Capacity S = new new Capacity (); 
        String filePath= "D: \\ JAVA \\ \\ java class source code" ; 
        s.getFiles (filePath); 
    } 

}

Run tests:

 

 

 2, write a file encryption program, encryption and decryption complete work from the command line;

analysis of idea:

1), the statement of encryption and decryption keys.

2), the contents read from the initialization file, encrypted with the key stored in the encrypted file.

3), to read the content from the encrypted file, the file to the decryption key for decryption.

Source:

package com.me.afterclass;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Encryption {
    private static final int numOfEncAndDec=0x99;//加密解密密钥
     private static int dataOfFile=0;//文件字节内容

     public static void main(String[] args) {
      File srcFile=new File("Initialization.txt");//初始化文件
      File encFile=new File("Encryption.txt"); //加密文件
      File decFile=new File("Decryption.txt");  //解密文件
      
      try {
       EncFile(srcFile,encFile);  //加密操作
       DecFile(encFile,decFile);
      }catch(Exception e) {
       e.printStackTrace();
      }
     }
     private static void EncFile(File srcFile,File encFile)throws Exception{
      if(!srcFile.exists()) {
       System.out.println("source file not exixt"); 
       } 
      IF (! ) {EncFile.exists () 
       System.out.println ( "Created the encrypt File" ); 
       encFile.createNewFile (); // if no encrypted file, create a new encrypted file 
      } 
      the InputStream FIS = new new the FileInputStream ( srcFile); 
      the OutputStream fos = new new a FileOutputStream (encFile); 
      
      the while ((dataOfFile = fis.read ())> -. 1) { // when contents of the file to read when 
       fos.write (dataOfFile ^ numOfEncAndDec); // read-out writes the content encrypted 
      } 
      fis.close (); 
      fos.flush (); 
      fos.close (); 
     } 
     Private static void DecFile(File encFile,File decFile)throws Exception{
      if(!encFile.exists()) {
       System.out.println("encrypt file not exixt");
      }
      if(!decFile.exists()) {
       System.out.println("decrypt file created");
       decFile.createNewFile();
      }
      InputStream fis=new FileInputStream(encFile);
      OutputStream fos=new FileOutputStream(decFile);
      
      while((dataOfFile=fis.read())>-1) {
       fos.write(dataOfFile^numOfEncAndDec);
      }
      fis.close();
      fos.flush();
      fos.close();
     }

}

Run tests:

 

 

 

 

 

 

 

 

 3, write a file splitting tool can split a large file into multiple smaller files. And can again merge them together to get the complete file.

Source:

Package com.me.afterclass; 

Import java.io.BufferedReader;
 Import java.io.BufferedWriter;
 Import java.io.File;
 Import a java.io.FileInputStream;
 Import java.io.FileNotFoundException;
 Import java.io.FileWriter;
 Import java.io.IOException;
 Import java.io.InputStreamReader; 

public  class Partition {
     public  static  void main (String [] args) {
         // statement:! ! partitionFile (original large file, the path of small files stored after cutting, cutting the number of rows specified) 
        partitionFile ( "D: \\ 3 \\ test \\ transfer station Market St. .txt", "D: \\ transfer station 3 T Test \\ \\ ", 30000  );
    }

    private static void partitionFile(String src, String endsrc, int num) {
        FileInputStream fis = null;
        File file = null;
        int name=1;
        try {
            InputStreamReader reader = new InputStreamReader(  new FileInputStream(src),"GBK"); 
            BufferedReader br = new BufferedReader(reader);//读取文件内的内容 
            String str=br.readLine();
            File = new newFile (src);
             the while (! Str = null ) { 
                
                // find the original documents to each file name and file type, file name for the next little to prepare 
                String NAME2 = file.getName ();
                 int lastIndexOf = name2.lastIndexOf ( "." ); 
                String the substring = name2.substring (0 , lastIndexOf); 
                String substring2 = name2.substring (lastIndexOf, name2.length ()); 
                FileWriter Write = new new FileWriter (endsrc + "\\\\" the substring + + "-" + name + substring2); 
                BufferedWriter, OUT = new new BufferedWriter(write);
                for(int k=0;k<num;k++) {
                    out.write(str);
                    str=br.readLine();
                    if(str == null) {
                        break;
                    }
                }
                //结束资源
                out.close();
                name++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    //结束资源
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Run tests:

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/20183544-wangzhengshuai/p/11793193.html