一个常用的文件操作类

package com...utils.file;

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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import wfc.service.database.Sequence;

public class ReadAndWriteFile {
    
    private static JSONArray jsonArray = new JSONArray();
    
    /**
     * 遍历文件夹所有的文件 获取文件名
     * @param filepath
     * @return
     * @throws FileNotFoundException
     */
    public static JSONArray readfilename(String filepath) throws FileNotFoundException {
    
        try {
            File file = new File(filepath);
            if (!file.isDirectory()) {
                System.out.println("文件");
                System.out.println("path=" + file.getPath());
                System.out.println("absolutepath=" + file.getAbsolutePath());
                System.out.println("name=" + file.getName());

            } else if (file.isDirectory()) {//是文件夹
                String[] filelist = file.list();
                //
                int filelength = filelist.length;
                for (int i = 0; i < filelength; i++) {
                    JSONObject json = new JSONObject();
                    File readfile = new File(filepath + "\\" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        String filename = readfile.getName();
                        json.put("name", filename);
                        jsonArray.add(json);
                        //是文件夹继续遍历
                    } else if (readfile.isDirectory()) {
                        readfilename(filepath + "\\" + filelist[i]);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("readfilename()   Exception:" + e.getMessage());
        }
        return jsonArray;
    }
    
    /**
     * 删除文件
     * @param delpath
     */
    public static void deleteFile(String delpath) {
        try {
            File file = new File(delpath);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            System.out.println("deletefile()  Exception:" + e.getMessage());
        }
    }

    /**
     * 更改文件名
     * @param filePath
     * @param oldFileName
     * @param newFilename
     */
    public static void renameFile(String filePath, String oldFileName, String newFilename) {
        try {
            File file = new File(filePath + oldFileName);
            if (file.exists()) {
                file.renameTo(new File(filePath + newFilename));
            }
        } catch (Exception e) {
            System.out.println("renamefile()  Exception:" + e.getMessage());
        }
    }

     /**
      * 判断文件夹下是否存在文件
      * @param filepath
      * @return
      */
    public static boolean hasFile(String filepath) {
         File start = new File(filepath);
         String[] filePath = start.list();//获取该文件夹下的所有文件以及目录的名字
         if(filePath.length>0){
             return true;
         }
         return false;
    }
    
    
    /**
     * 文件的拷贝(单个)
     * @param sourcePath
     * @param newPath
     * @return
     */
    public static boolean copyFile(String sourcePath, String newPath) {
        boolean flag = false;
        File readfile = new File(sourcePath);
        File newFile = new File(newPath);
        if(!readfile.exists()) {
            return flag;
        }
        BufferedWriter bufferedWriter = null;
        Writer writer = null;
        FileOutputStream fileOutputStream = null;
        BufferedReader bufferedReader = null;
        InputStream  in =null;
        try{
            in = new FileInputStream(readfile);
            fileOutputStream = new FileOutputStream(newFile, true);
            writer = new OutputStreamWriter(fileOutputStream,"GBK");
            bufferedWriter = new BufferedWriter(writer);
            bufferedReader = new BufferedReader(new InputStreamReader(in,"GBK"));
            
            String line = null;
            while((line = bufferedReader.readLine()) != null){
                bufferedWriter.write(line);
                bufferedWriter.newLine();
                bufferedWriter.flush();
            }
            flag = true;    
        } catch(IOException e) {
            flag = false;
            e.printStackTrace();
        } finally {
            try {
                if(bufferedWriter != null){
                    bufferedWriter.close();
                }
                if(bufferedReader != null){
                    bufferedReader.close();
                }
                if(writer != null){
                    writer.close();
                }
                if(fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }
    
    
    /**
     * 文件复制(多个)
     * @param sourcePathDir
     * @param newPathDir
     */
     public static void copyDir(String sourcePathDir, String newPathDir) {
            File start = new File(sourcePathDir);
            File end = new File(newPathDir);
            String[] filePath = start.list();//获取该文件夹下的所有文件以及目录的名字
            if(!end.exists()) {
                end.mkdir();
            }
            boolean flag = false;
            for(String temp : filePath) {
                //添加满足情况的条件
                if(new File(sourcePathDir + temp).isDirectory()){
                    System.out.println("文件:"+temp+" 是文件夹");
                    return;
                }
                if(new File(sourcePathDir + temp ).isFile()&& temp.endsWith(".js")) {
                    //为文件则进行拷贝
                    flag = copyFile(sourcePathDir + temp, newPathDir + temp );
                }
                String Str="";
                if(flag){
                    Str = readJsonFile(sourcePathDir + temp);
                    temp = temp.substring(0,temp.indexOf("."));
                    writeJsonString(newPathDir +  temp +"--copy.js", Str);
                    //删除源文件
                    deleteFile(sourcePathDir  + temp+".js");
                    deleteFile(newPathDir  + temp+".js");
                    System.out.println("文件:" + temp + ",复制成功!");
                }else{
                    System.out.println("文件:" + temp + ",复制失败!");
                }
            }
        }
     
     public static String readJsonFile(String fileName) {
            String jsonStr = "";
            try {
                File jsonFile = new File(fileName);
                if (!jsonFile.exists()) {
                    return "";
                }
                Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "GBK");
                int ch = 0;
                StringBuffer sb = new StringBuffer();
                while ((ch = reader.read()) != -1) {
                    sb.append((char) ch);
                }
                reader.close();
                jsonStr = sb.toString();
                return jsonStr;
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
        }
     
        public static void writeJsonString(String filepath, String jsonObject) {
            try {
                File file = new File(filepath);
                if (!file.exists())// 判断文件是否存在,若不存在则新建
                {
                    file.createNewFile();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(file);// 实例化FileOutputStream
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "GBK");// 将字符流转换为字节流
                BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);// 创建字符缓冲输出流对象
                String jsonString = jsonObject.toString();// 将jsonObject数组转化为字符串
                bufferedWriter.write(jsonString);// 将格式化的jsonarray字符串写入文件
                bufferedWriter.flush();// 清空缓冲区,强制输出数据
                bufferedWriter.close();// 关闭输出流
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
     
     public static void writeJsonString(String filepath,String oauthId, JSONArray jsonArray) throws IOException {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String dateString = sdf.format(date);
            String code = getSequenceCode(dateString);
            File file = new File(filepath + oauthId+"-"+dateString + code + ".json");
            if (!file.exists())// 判断文件是否存在,若不存在则新建
            {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);// 实例化FileOutputStream
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "GBK");// 将字符流转换为字节流
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);// 创建字符缓冲输出流对象
            String jsonString = jsonArray.toString();// 将jsonarray数组转化为字符串
            bufferedWriter.write(jsonString);// 将格式化的jsonarray字符串写入文件
            bufferedWriter.flush();// 清空缓冲区,强制输出数据
            bufferedWriter.close();// 关闭输出流
        }

        //自增
        public static String getSequenceCode(String type) {
                return String.format("%08d", Sequence.getNextValue(type));
        }

        
        
}

 

posted @ 2020-09-21 17:44  Li&Fan  阅读(231)  评论(0编辑  收藏  举报