动手动脑5

  WatchService是监听文件的。对于文件的监听操作共三步:实现service

  1. WatchService 实例化
  2. 使用 Path 来指定要监控的目录
  3. 将 Path 注册到 WatchService

  WatchService可以同时监听多个文件。

源代码:

public static void main(String[] args) {
        //创建一个WatchService对象,此对象将用于管理特定文件夹的变动信息队列。
        try(WatchService service=FileSystems.getDefault().newWatchService()) {
            //此集合可保存多个文件夹的监控信息,当前只使用了一个
            Map<WatchKey, Path> keyMap=new HashMap<>();
            Path path=Paths.get("D:\test");
            //设置WatchService对象管理的内部队列,将保存指定的文件夹的创建、删除和修改事件信息
            //返回的WatchKey对象可用于从事件队列中获取事件对象
            WatchKey key=path.register(service, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
            keyMap.put(key, path);
            
            do {
                //开始监控,阻塞等待,当感兴趣的事件发生时,take()方法返回。
                key=service.take();
                Path eventDir=keyMap.get(key);
                //从事件队列中提取所有的事件
                for (WatchEvent<?> event : key.pollEvents()) {
                    //是什么类型的事件?
                    WatchEvent.Kind<?> kind=event.kind();
                    //是哪个对象发生了变动?
                    Path eventPath=(Path)event.context();
                    System.out.println(eventDir+":"+kind+":"+eventPath);
                }
            } while (key.reset()); //reset方法重置此对象,让其可以重新接收信息
            
        } catch (Exception e) {
            
        }

    }

  使用Path.register() 方法注册要监控指定目录的那些事件(创建、修改、删除)

  StandardWatchEventKinds.ENTRYCREATE //创建StandardWatchEventKinds.ENTRYMODIFY //修改StandardWatchEventKinds.ENTRY_DELETE //删除

  对于文件监听器还是有很多不懂的地方,在以后的学习中我会逐渐学会这些。

编写一个程序,计算文件大小;

package Tuorial05;

import java.io.File;
import java.io.IOException;

public class FileSize {

    public static void main(String[] args) throws IOException{
        FileSize fs=new FileSize();
        double all= fs.getSize(new File("g://java_Tutorial"));
        System.out.println(all);
    }
    public  double getSize(File file) {
        double ss=0;
        if (file.exists()) {  
            //如果是目录则递归计算其内容的总大小,如果是文件则直接返回其大小  
            if (!file.isFile()) {  
                //获取文件大小  
                File[] fl = file.listFiles();  
                for (File f : fl)  
                    ss += getSize(f);  
                return  ss;  
            } else {  
                ss = (double) file.length() / 1024 / 1024;  
                System.out.println(file.getName() + " : " + ss + "MB");  
                return ss;  
            }  
        } else {  
            System.out.println("文件或者文件夹不存在,请检查路径是否正确!");  
            return 0.0;  
        }  
    }
}

文件加解密操作:

package Tuorial05;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Fileclock {
    
  private static int dataOfFile=0;//文件字节内容
  private static final int numOfEncAndDec=0x99;
  public static void main(String[] args) {
   File srcFile=new File("textpassword0.txt");//初始化文件
   File encFile=new File("textpossword.txt"); //加密文件
   File decFile=new File("textpossword1.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("encrypt file created");
    encFile.createNewFile();//若无加密文件,新建一个加密文件
   }
   InputStream fis=new FileInputStream(srcFile);
   OutputStream fos=new FileOutputStream(encFile);
   
   while((dataOfFile=fis.read())>-1) {//当读到文件内容时
    fos.write(dataOfFile^numOfEncAndDec);//将读出的内容加密后写入
   }
   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();
  }

}

文件分割工具,大文件分割成小文件,小文件合并成一个完整的文化:

package Tuorial05;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class FileSplit {
 
    private static int nameend = 1;//记录将要在旧名字上加上的编号以生成新文件
    
    public static void main(String[] args) {
        //File ifile = new File("d:\test\iabc.txt");
        //File ifile = new File("d:\test\iabc.txt.txt.txt.txt");
        File ifile = new File("textpassword0.txt");
        File ofile = new File("textpassword3.txt");
        FileSplit fs = new FileSplit();
        fs.fileSplitMethod(ifile, ofile, 1024*1024*2);
    }
    

    public boolean fileSplitMethod(File    ifile,File ofile,long filesize){
        boolean success = false;
        if(!ifile.exists() || !ifile.isFile() || !ofile.exists() || !ofile.isDirectory() ||  filesize <= 0)
            return success;
        int bufl = 1024; //缓冲字节数组的长度
        if(filesize < bufl)
            bufl = (int) filesize;
        byte[] buf = new byte[bufl];//字节缓冲数组
        int length = 0;//记录当前读取的字节数
        int size = 0;//记录当前文件字节数
        long readsize = 0;
        
        FileInputStream fis = null;
        FileOutputStream fos = null;
        
        try {
            fis = new FileInputStream(ifile);
            fos = new FileOutputStream(getNewFile(ifile,ofile));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            while((length = fis.read(buf)) != -1){
                fos.write(buf,0,length);
                size += length;
                readsize += length;//记录总已经读取字节数
                if((size + bufl) > filesize && readsize < ifile.length()){//如果再读一个数组会大于最大单个文件大小,并且还有未读字节,则创建新的fos。
                    fos.flush();//将缓冲中的写入文件
                    fos.close();//关闭这个输出流
                    fos = new FileOutputStream(getNewFile(ifile,ofile));//重新创建新的输出流
                    size = 0;
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return success;
    }
    
    public File getNewFile(File    ifile,File ofile){
        File file = null;
        String oldname = ifile.getName();//得到旧名字,新名字将在旧名字上加上数字
        String newfilepath = ofile.getPath() + "\";//用于保存新的file路径
        int endIndex = oldname.lastIndexOf(".");
        if(endIndex > 0){
            String oldnameend = oldname.substring(endIndex, oldname.length());//保存扩展名
            oldname = oldname.substring(0, endIndex);//保存最后一个点左边的名字
            newfilepath += oldname + nameend++ + oldnameend;//新路径
        }else
            newfilepath += oldname + nameend++;
        file = new File(newfilepath);
        return file;
    }
}
原文地址:https://www.cnblogs.com/huan-ch/p/9981302.html