zoukankan      html  css  js  c++  java
  • 自写文件小工具类

      参考了一些关于文件操作的类,但是感觉并不怎么全面,就整合一些代码,并加上自己的一些思路,就成了现在的一个小工具了,如果有好的建议,或者代码中有什么遗漏欢迎指正,如果有涉及到版权,希望能够及时联系.

    package com.wk.mothod;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.util.UUID;
    
    //创建新文件和目录
    public class MyFileUtil {
        // 验证字符串是否为正确路径名的正则表达式
        private static String matches = "[A-Za-z]:[\\|\/][^:?"><*]*";
        // 通过 sPath.matches(matches) 方法的返回值判断是否正确
        // sPath 为路径字符串
        boolean flag = false;
        File file;
    
        public boolean DeleteFolder(String deletePath) {// 根据路径删除指定的目录或文件,无论存在与否
            flag = false;
            if (deletePath.matches(matches)) {
                file = new File(deletePath);
                if (!file.exists()) {// 判断目录或文件是否存在
                    return flag; // 不存在返回 false
                } else {
    
                    if (file.isFile()) {// 判断是否为文件
                        return deleteFile(deletePath);// 为文件时调用删除文件方法
                    } else {
                        return deleteDirectory(deletePath);// 为目录时调用删除目录方法
                    }
                }
            } else {
                System.out.println("要传入正确路径!");
                return false;
            }
        }
    
        public boolean deleteFile(String filePath) {// 删除单个文件
            flag = false;
            file = new File(filePath);
            if (file.isFile() && file.exists()) {// 路径为文件且不为空则进行删除
                file.delete();// 文件删除
                flag = true;
            }
            return flag;
        }
        public boolean existsFile(String filePath) {// 是否存在文件路径
            flag = false;
            file = new File(filePath);
            if (file.isFile() && file.exists()) {
                //file.delete();// 文件删除
                flag = true;
            }
            return flag;
        }
        public boolean existsDictionary(String filePath) {// 是否存在文件路径
            flag = false;
            file = new File(filePath);
            if (file.isDirectory() && file.exists()) {
                //file.delete();// 文件删除
                flag = true;
            }
            return flag;
        }
    
        public boolean deleteDirectory(String dirPath) {// 删除目录(文件夹)以及目录下的文件
            // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
            if (!dirPath.endsWith(File.separator)) {
                dirPath = dirPath + File.separator;
            }
            File dirFile = new File(dirPath);
            // 如果dir对应的文件不存在,或者不是一个目录,则退出
            if (!dirFile.exists() || !dirFile.isDirectory()) {
                return false;
            }
            flag = true;
            File[] files = dirFile.listFiles();// 获得传入路径下的所有文件
            for (int i = 0; i < files.length; i++) {// 循环遍历删除文件夹下的所有文件(包括子目录)
                if (files[i].isFile()) {// 删除子文件
                    flag = deleteFile(files[i].getAbsolutePath());
                    System.out.println(files[i].getAbsolutePath() + " Delete Succeed!");
                    if (!flag)
                        break;// 如果删除失败,则跳出
                } else {// 运用递归,删除子目录
                    flag = deleteDirectory(files[i].getAbsolutePath());
                    System.out.println(files[i].getAbsolutePath() + " Delete Succeed!");
                    if (!flag)
                        break;// 如果删除失败,则跳出
                }
            }
            if (!flag)
                return false;
            if (dirFile.delete()) {// 删除当前目录
                System.out.println(dirPath + " Delete Succeed!");
                return true;
            } else {
                return false;
            }
        }
    
        // 创建单个文件
        public static boolean createEmptyFile(String filePath) {
            File file = new File(filePath);
            if (file.exists()) {// 判断文件是否存在
                System.out.println("File already exist " + filePath);
                return false;
            }
            if (filePath.endsWith(File.separator)) {// 判断文件是否为目录
                System.out.println("File cann't be null!");
                return false;
            }
            if (!file.getParentFile().exists()) {// 判断目标文件所在的目录是否存在
                // 如果目标文件所在的文件夹不存在,则创建父文件夹
                System.out.println("Ready to creat the dictionary of the file for it not exist.");
                if (!file.getParentFile().mkdirs()) {// 判断创建目录是否成功
                    System.out.println("Creat Dictionary failed!");
                    return false;
                }
            }
            try {
                if (file.createNewFile()) {// 创建目标文件
                    System.out.println("Creat File succeed:" + filePath);
                    return true;
                } else {
                    System.out.println("Creat File failed!");
                    return false;
                }
            } catch (IOException e) {// 捕获异常
                e.printStackTrace();
                System.out.println("Creat File failed!" + e.getMessage());
                return false;
            }
        }
        
        /**
         * 创建文件
         * @param fileName  文件名称
         * @param filecontent   文件内容
         * @return  是否创建成功,成功则返回true
         */
        public static boolean createFile(String filePath,String filecontent){
            File file = new File(filePath);
            if (file.exists()) {// 判断文件是否存在
                System.out.println("File has exist:" + filePath);
                return false;
            }
            if (filePath.endsWith(File.separator)) {// 判断文件是否为目录
                System.out.println("File can't be a dictionary!");
                return false;
            }
            if (!file.getParentFile().exists()) {// 判断目标文件所在的目录是否存在
                // 如果目标文件所在的文件夹不存在,则创建父文件夹
                System.out.println("Read to creat the dictionary of the file for it not exist!");
                if (!file.getParentFile().mkdirs()) {// 判断创建目录是否成功
                    System.out.println("Creat dictionary of the file failed!");
                    return false;
                }
            }
            try {
                if (file.createNewFile()) {// 创建目标文件
                    System.out.println("Creat File succeed:" + filePath);
                    writeFileContent(filePath, filecontent);
                    return true;
                } else {
                    System.out.println("Creat File failed!");
                    return false;
                }
            } catch (IOException e) {// 捕获异常
                e.printStackTrace();
                System.out.println("Creat File failed:" + e.getMessage());
                return false;
            }
        }
    
        
        /**
         * 向文件中写入内容
         * @param filepath 文件路径与名称
         * @param newstr  写入的内容
         * @return
         * @throws IOException
         */
        public static boolean writeFileContent(String filepath,String newstr) throws IOException{
            Boolean bool = false;
            String filein = newstr+"
    ";//新写入的行,换行
            String temp  = "";
            
            FileInputStream fis = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
            FileOutputStream fos  = null;
            PrintWriter pw = null;
            try {
                File file = new File(filepath);//文件路径(包括文件名称)
                //将文件读入输入流
                fis = new FileInputStream(file);
                isr = new InputStreamReader(fis);
                br = new BufferedReader(isr);
                StringBuffer buffer = new StringBuffer();
                
                //文件原有内容
                for(int i=0;(temp =br.readLine())!=null;i++){
                    buffer.append(temp);
                    // 行与行之间的分隔符 相当于“
    ”
                    buffer = buffer.append(System.getProperty("line.separator"));
                }
                buffer.append(filein);
                
                fos = new FileOutputStream(file);
                pw = new PrintWriter(fos);
                pw.write(buffer.toString().toCharArray());
                pw.flush();
                bool = true;
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }finally {
                //不要忘记关闭
                if (pw != null) {
                    pw.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
            return bool;
        }
        // 创建目录
        public static boolean createDir(String destDirName) {
            File dir = new File(destDirName);
            if (dir.exists()) {// 判断目录是否存在
                if(dir.isFile()){
                    System.out.println("Creat Dictionary failed for it has a same name file!");
                }else{
                    System.out.println("Creat Dictionary failed for it has exist!");
                }
                return false;
            }
            if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
                destDirName = destDirName + File.separator;
            }
            if (dir.mkdirs()) {// 创建目标目录
                System.out.println("Creat Dictionary succeed!" + destDirName);
                return true;
            } else {
                System.out.println("Creat Dictionary failed!");
                return false;
            }
        }
    
        // 创建临时文件
        public static String createTempEmptyFile(String prefix, String suffix,
                String dirName) {
            File tempFile = null;
            if (dirName == null) {// 目录如果为空
                try {
                    tempFile = File.createTempFile(prefix, suffix);// 在默认文件夹下创建临时文件
                    return tempFile.getCanonicalPath();// 返回临时文件的路径
                } catch (IOException e) {// 捕获异常
                    e.printStackTrace();
                    System.out.println("创建临时文件失败:" + e.getMessage());
                    return null;
                }
            } else {
                // 指定目录存在
                File dir = new File(dirName);// 创建目录
                if (!dir.exists()) {
                    // 如果目录不存在则创建目录
                    if (MyFileUtil.createDir(dirName)) {
                        System.out.println("创建临时文件失败,不能创建临时文件所在的目录!");
                        return null;
                    }
                }
                try {
                    tempFile = File.createTempFile(prefix, suffix, dir);// 在指定目录下创建临时文件
                    return tempFile.getCanonicalPath();// 返回临时文件的路径
                } catch (IOException e) {// 捕获异常
                    e.printStackTrace();
                    System.out.println("创建临时文件失败!" + e.getMessage());
                    return null;
                }
            }
        }
    
        public static void main(String[] args) {
             UUID uuid = UUID.randomUUID();
            String dirName = "E:\createFile\";// 创建目录
            MyFileUtil mf=new MyFileUtil();
            mf.createDir(dirName);// 调用方法创建目录
            String fileName = dirName + "\fije1.txt";// 创建文件
            mf.createEmptyFile(fileName);// 调用方法创建文件
            String prefix = "temp";// 创建临时文件
            String surfix = ".txt";// 后缀
            mf.createFile(dirName+"test.txt","abcd");
            for (int i = 0; i < 10; i++) {// 循环创建多个文件
                System.out.println("Creat a test temp file: "// 调用方法创建临时文件
                        + mf.createTempEmptyFile(prefix, surfix,
                                dirName));
                
                mf.createEmptyFile(dirName+uuid.randomUUID()+"test.txt");
                
                try {
                    mf.writeFileContent(dirName+"test.txt","abcd");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            mf.DeleteFolder(dirName);
        }
    }
  • 相关阅读:
    HTML5项目笔记7:使用HTML5 WebStorage API构建与.NET对应的会话机制 Hello
    论设计模式和分析模式
    昨天我做了点什么事情啊?
    时间,时间,还是时间
    人生需要规划
    突然想起今天的博客汇报没写
    昨天看了熊猫大侠
    双休日往往会忘了写日志
    老婆说我是缺心眼!
    要下班了才想起没写报告
  • 原文地址:https://www.cnblogs.com/wangkun1993/p/7199326.html
Copyright © 2011-2022 走看看