java中 文件及文件夹的操作相关操作

package lesson09_io.my;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;   
import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;   
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;  
/**
 * 文件的相关操作
 * @author 1279938986@qq.com
 *
 */
public class MyFile {

    //文件的操作
    /**
     * 增删改查  
     * 增:(创建文件夹)mkdir() mkdirs()  创建文件前提条件目录非空:  createNewFile()        
     * 删:delete();  只能删除单个空的文件夹,对于非空文件夹只能先删除子文件及文件夹
     * 改:renameto(File dest)  修改文件的名字为参数名字注意如果原文件名和目标文件名不在统一目录下则是移动并改名1
     * 查:1.exist() 文件是否存在
     *       2.自定义方法findFiles(要查找的文件的目录, 要查找的文件关键词支持*和?)
     * 获取文件的父目录:
     *        1.String getParent()  
     *     2. File getParentFile()
     *获取文件的路径
     *     1.String getPath()           将此抽象路径名转换为一个路径名字符串。 相对路径
     *     2.File getAbsoluteFile()          返回此抽象路径名的绝对路径名形式。  绝对路径
     *          String getAbsolutePath()     返回此抽象路径名的绝对路径名字符串。 绝对路径
     *      FIles 从以下版本开始: 1.7
     * 复制文件  Files   public static Path copy(Path source,
                        Path target,
                        CopyOption... options)
                 throws IOException
                 参考:public static void copyFile(File source, File dest)
        throws IOException {    
        Files.copy(source.toPath(), dest.toPath());
        }
        
            复制一个目录及其子目录、文件到另外一个目录         copyFolder(File src, File dest)
        
                  

     * 移动文件 Files  move(Path source, Path target, CopyOption... options) 将文件移动或重命名为目标文件。

     * 读写文件:1.按字节读写  FileInputStream FileOutputStream 主要是针对非文本类文件如:图像音视频文件及其他非文本类文件
     *           2.按字符读写文件 主要是针对文本类文件 FileReader与FileWrite  BufferedReader与BufferedWrite
     *

     */    
    /**
     * 读写文件主要针对非文本类文件
     * @throws IOException
     */
    public static void  readAndWriteByte() throws IOException
    {
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream("d:/abc.jpg"));
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("d:/abcd.jpg"));
        byte[] buf=new byte[1024];
        int count=-1;
        while((count=bis.read(buf))!=-1){
            bos.write(buf, 0, count);            
        }
        bos.flush();
        bis.close();
        bos.close();        
    }
    public static void  readAndWriteChar() throws IOException{
        //BufferedReader br=new BufferedReader(new FileReader(new File("D:/abc.txt")));
        BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(new File("D:/abcd.txt")), "GB2312"));
        BufferedWriter bw=new BufferedWriter(new FileWriter(new File("D:/abcd.txt")));
        char []cbuf=new char[1024];
        int len=-1;
        
        while((len=br.read(cbuf))!=-1){
            //System.out.println(new String(new String(cbuf,0,len).getBytes(),"utf-8"));
            //System.out.println(new String(cbuf,0,len).getBytes().);
            bw.write(cbuf, 0, len);
            
        }
        bw.flush();
        br.close();
        bw.close();
        
    }
    
    
    
    /**
     * 删除文件及文件夹
     *
     * @param file
     */
    public static void delFile(File file){
        if (file.exists()) {
            if(file.isDirectory()){
                File[] files = file.listFiles();
                for(int i=0;i<files.length;i++){
                    delFile(files[i]);
                }
                System.out.println(file.getAbsolutePath()+"  is deleted");
                file.delete();            
            }else {
                System.out.println(file.getAbsolutePath()+"  is deleted");
                file.delete();            
            }
        }else {
            System.out.println(file.getAbsolutePath()+" 不存在无法删除");
        }
        
    }
    public static void moveFile(File source,File dest) throws IOException{
        
            Files.move(source.toPath(),dest.toPath());
        
        
    }
    /**
     * 文件和文件夹的文件的复制
     * @param source
     * @param dest
     * @throws IOException
     * 目前只能做空目录不能做子目录
     */
    public static void copyFile(File source, File dest)
            throws IOException {    
            Files.copy(source.toPath(), dest.toPath(),StandardCopyOption.COPY_ATTRIBUTES);
            }
    
    
    /**
     * 递归查找文件并打印文件
     *
     * @param baseDirName
     *            查找的文件夹路径
     * @param targetFileName
     *            需要查找的文件名
     * @param fileList
     *            查找到的文件集合
     *
     */
    public static void findFiles(String baseDirName, String targetFileName)  {
        List  fileList = new ArrayList();
        findFiles(baseDirName, targetFileName, fileList);
        List resultList = fileList;
        if (resultList.size() == 0) {
            System.out.println("No File Fount.");
        } else {
            for (int i = 0; i < resultList.size(); i++) {
                System.out.println(resultList.get(i));// 显示查找结果。
            }
        }
        /*  将检索到的文件信息写入到某c:\abc.txt文件中 次功能为附加功能         
        OutputStreamWriter osw=null;
        try {
            osw=new OutputStreamWriter(new FileOutputStream("c:/abc.txt"), "utf-8");
            for (int i = 0; i < resultList.size(); i++) {
                File file=(File) resultList.get(i);// 显示查找结果。
                String filename=file.getAbsoluteFile()+"\r\n";
                osw.write(filename);
                
            }
            osw.flush();
        }catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        finally{
            try {
                if (osw!=null) {
                    osw.close();                    
                }                
            } catch (IOException e) {                
                e.printStackTrace();
            }
        }
        */
        
        
        
    }

    /**
     * 递归查找文件
     *
     * @param baseDirName
     *            查找的文件夹路径
     * @param targetFileName
     *            需要查找的文件名
     * @param fileList
     *            查找到的文件集合
     *
     */
    public static void findFiles(String baseDirName, String targetFileName, List<File> fileList)  {

        File baseDir = new File(baseDirName); // 创建一个File对象
        if (!baseDir.exists() || !baseDir.isDirectory()) { // 判断目录是否存在
            System.out.println("文件查找失败:" + baseDirName + "不是一个目录!");
            return;
        }
        String tempName = null;
        // 判断目录是否存在
        File tempFile;
        

        File[] files = baseDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            tempFile = files[i];
            if (tempFile.isDirectory()) {
                findFiles(tempFile.getAbsolutePath(), targetFileName, fileList);
            } else if (tempFile.isFile()) {
                tempName = tempFile.getName();
                if (wildcardMatch(targetFileName, tempName)) {
                    // 匹配成功,将文件名添加到结果集
                    fileList.add(tempFile.getAbsoluteFile());
                }
            }
        }

    }

    /**
     * 通配符匹配
     *
     * @param pattern
     *            通配符模式
     * @param str
     *            待匹配的字符串
     * @return 匹配成功则返回true,否则返回false
     */
    private static boolean wildcardMatch(String pattern, String str) {
        int patternLength = pattern.length();
        int strLength = str.length();
        int strIndex = 0;
        char ch;
        for (int patternIndex = 0; patternIndex < patternLength; patternIndex++) {
            ch = pattern.charAt(patternIndex);
            if (ch == '*') {
                // 通配符星号*表示可以匹配任意多个字符
                while (strIndex < strLength) {
                    if (wildcardMatch(pattern.substring(patternIndex + 1), str.substring(strIndex))) {
                        return true;
                    }
                    strIndex++;
                }
            } else if (ch == '?') {
                // 通配符问号?表示匹配任意一个字符
                strIndex++;
                if (strIndex > strLength) {
                    // 表示str中已经没有字符匹配?了。
                    return false;
                }
            } else {
                if ((strIndex >= strLength) || (ch != str.charAt(strIndex))) {
                    return false;
                }
                strIndex++;
            }
        }
        return (strIndex == strLength);
    }
    
    

    /**
     * 复制一个目录及其子目录、文件到另外一个目录
     * @param src
     * @param dest
     * @throws IOException
     */  
    public static  void copyFolder(File src, File dest) throws IOException {  
        if (src.isDirectory()) {  
            if (!dest.exists()) {  
                dest.mkdir();  
            }  
            String files[] = src.list();  
            for (String file : files) {  
                File srcFile = new File(src, file);  
                File destFile = new File(dest, file);  
                // 递归复制  
                copyFolder(srcFile, destFile);  
            }  
        } else {  
            InputStream in = new FileInputStream(src);  
            OutputStream out = new FileOutputStream(dest);  
      
            byte[] buffer = new byte[1024];  
      
            int length;  
              
            while ((length = in.read(buffer)) > 0) {  
                out.write(buffer, 0, length);  
            }  
            in.close();  
            out.close();  
        }  
    }  

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值