zoukankan      html  css  js  c++  java
  • JAVA FileUtils(文件读写以及操作工具类)

    文件操作常用功能:

      1 package com.suning.yypt.business.report;
      2 
      3 import java.io.*;
      4 import java.util.*;
      5 
      6 @SuppressWarnings({"resource","unused"})
      7 public class FileUtils {
      8 
      9     /**
     10      * 获取windows/linux的项目根目录
     11      * @return
     12      */
     13     public static String getConTextPath(){
     14         String fileUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath();
     15         if("usr".equals(fileUrl.substring(1,4))){
     16             fileUrl = (fileUrl.substring(0,fileUrl.length()-16));//linux
     17         }else{
     18             fileUrl = (fileUrl.substring(1,fileUrl.length()-16));//windows
     19         }
     20         return fileUrl;
     21     }
     22 
     23     /**
     24      * 字符串转数组
     25      * @param str 字符串
     26      * @param splitStr 分隔符
     27      * @return
     28      */
     29     public static String[] StringToArray(String str,String splitStr){
     30         String[] arrayStr = null;
     31         if(!"".equals(str) && str != null){
     32             if(str.indexOf(splitStr)!=-1){
     33                 arrayStr = str.split(splitStr);
     34             }else{
     35                 arrayStr = new String[1];
     36                 arrayStr[0] = str;
     37             }
     38         }
     39         return arrayStr;
     40     }
     41 
     42     /**
     43      * 读取文件
     44      *
     45      * @param Path
     46      * @return
     47      */
     48     public static String ReadFile(String Path) {
     49         BufferedReader reader = null;
     50         String laststr = "";
     51         try {
     52             FileInputStream fileInputStream = new FileInputStream(Path);
     53             InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
     54             reader = new BufferedReader(inputStreamReader);
     55             String tempString = null;
     56             while ((tempString = reader.readLine()) != null) {
     57                 laststr += tempString;
     58             }
     59             reader.close();
     60         } catch (IOException e) {
     61             e.printStackTrace();
     62         } finally {
     63             if (reader != null) {
     64                 try {
     65                     reader.close();
     66                 } catch (IOException e) {
     67                     e.printStackTrace();
     68                 }
     69             }
     70         }
     71         return laststr;
     72     }
     73 
     74     /**
     75      * 获取文件夹下所有文件的名称 + 模糊查询(当不需要模糊查询时,queryStr传空或null即可)
     76      * 1.当路径不存在时,map返回retType值为1
     77      * 2.当路径为文件路径时,map返回retType值为2,文件名fileName值为文件名
     78      * 3.当路径下有文件夹时,map返回retType值为3,文件名列表fileNameList,文件夹名列表folderNameList
     79      * @param folderPath 路径
     80      * @param queryStr 模糊查询字符串
     81      * @return
     82      */
     83     public static HashMap<String, Object> getFilesName(String folderPath , String queryStr) {
     84         HashMap<String, Object> map = new HashMap<>();
     85         List<String> fileNameList = new ArrayList<>();//文件名列表
     86         List<String> folderNameList = new ArrayList<>();//文件夹名列表
     87         File f = new File(folderPath);
     88         if (!f.exists()) { //路径不存在
     89             map.put("retType", "1");
     90         }else{
     91             boolean flag = f.isDirectory();
     92             if(flag==false){ //路径为文件
     93                 map.put("retType", "2");
     94                 map.put("fileName", f.getName());
     95             }else{ //路径为文件夹
     96                 map.put("retType", "3");
     97                 File fa[] = f.listFiles();
     98                 queryStr = queryStr==null ? "" : queryStr;//若queryStr传入为null,则替换为空(indexOf匹配值不能为null)
     99                 for (int i = 0; i < fa.length; i++) {
    100                     File fs = fa[i];
    101                     if(fs.getName().indexOf(queryStr)!=-1){
    102                         if (fs.isDirectory()) {
    103                             folderNameList.add(fs.getName());
    104                         } else {
    105                             fileNameList.add(fs.getName());
    106                         }
    107                     }
    108                 }
    109                 map.put("fileNameList", fileNameList);
    110                 map.put("folderNameList", folderNameList);
    111             }
    112         }
    113         return map;
    114     }
    115 
    116     /**
    117      * 以行为单位读取文件,读取到最后一行
    118      * @param filePath
    119      * @return
    120      */
    121     public static List<String> readFileContent(String filePath) {
    122         BufferedReader reader = null;
    123         List<String> listContent = new ArrayList<>();
    124         try {
    125             reader = new BufferedReader(new FileReader(filePath));
    126             String tempString = null;
    127             int line = 1;
    128             // 一次读入一行,直到读入null为文件结束
    129             while ((tempString = reader.readLine()) != null) {
    130                 listContent.add(tempString);
    131                 line++;
    132             }
    133             reader.close();
    134         } catch (IOException e) {
    135             e.printStackTrace();
    136         } finally {
    137             if (reader != null) {
    138                 try {
    139                     reader.close();
    140                 } catch (IOException e1) {
    141                 }
    142             }
    143         }
    144         return listContent;
    145     }
    146 
    147     /**
    148      * 读取指定行数据 ,注意:0为开始行
    149      * @param filePath
    150      * @param lineNumber
    151      * @return
    152      */
    153     public static String readLineContent(String filePath,int lineNumber){
    154         BufferedReader reader = null;
    155         String lineContent="";
    156         try {
    157             reader = new BufferedReader(new FileReader(filePath));
    158             int line=0;
    159             while(line<=lineNumber){
    160                 lineContent=reader.readLine();
    161                 line++;
    162             }
    163             reader.close();
    164         } catch (IOException e) {
    165             e.printStackTrace();
    166         } finally {
    167             if (reader != null) {
    168                 try {
    169                     reader.close();
    170                 } catch (IOException e1) {
    171                 }
    172             }
    173         }
    174         return lineContent;
    175     }
    176 
    177     /**
    178      * 读取从beginLine到endLine数据(包含beginLine和endLine),注意:0为开始行
    179      * @param filePath
    180      * @param beginLineNumber 开始行
    181      * @param endLineNumber 结束行
    182      * @return
    183      */
    184     public static List<String> readLinesContent(String filePath,int beginLineNumber,int endLineNumber){
    185         List<String> listContent = new ArrayList<>();
    186         try{
    187             int count = 0;
    188             BufferedReader reader = new BufferedReader(new FileReader(filePath));
    189             String content = reader.readLine();
    190             while(content !=null){
    191                 if(count >= beginLineNumber && count <=endLineNumber){
    192                     listContent.add(content);
    193                 }
    194                 content = reader.readLine();
    195                 count++;
    196             }
    197         } catch(Exception e){
    198         }
    199         return listContent;
    200     }
    201 
    202     /**
    203      * 读取若干文件中所有数据
    204      * @param listFilePath
    205      * @return
    206      */
    207     public static List<String> readFileContent_list(List<String> listFilePath) {
    208         List<String> listContent = new ArrayList<>();
    209         for(String filePath : listFilePath){
    210             File file = new File(filePath);
    211             BufferedReader reader = null;
    212             try {
    213                 reader = new BufferedReader(new FileReader(file));
    214                 String tempString = null;
    215                 int line = 1;
    216                 // 一次读入一行,直到读入null为文件结束
    217                 while ((tempString = reader.readLine()) != null) {
    218                     listContent.add(tempString);
    219                     line++;
    220                 }
    221                 reader.close();
    222             } catch (IOException e) {
    223                 e.printStackTrace();
    224             } finally {
    225                 if (reader != null) {
    226                     try {
    227                         reader.close();
    228                     } catch (IOException e1) {
    229                     }
    230                 }
    231             }
    232         }
    233         return listContent;
    234     }
    235 
    236     /**
    237      * 文件数据写入(如果文件夹和文件不存在,则先创建,再写入)
    238      * @param filePath
    239      * @param content
    240      * @param flag true:如果文件存在且存在内容,则内容换行追加;false:如果文件存在且存在内容,则内容替换
    241      */
    242     public static String fileLinesWrite(String filePath,String content,boolean flag){
    243         String filedo = "write";
    244         FileWriter fw = null;
    245         try {
    246             File file=new File(filePath);
    247             //如果文件夹不存在,则创建文件夹
    248             if (!file.getParentFile().exists()){
    249                 file.getParentFile().mkdirs();
    250             }
    251             if(!file.exists()){//如果文件不存在,则创建文件,写入第一行内容
    252                 file.createNewFile();
    253                 fw = new FileWriter(file);
    254                 filedo = "create";
    255             }else{//如果文件存在,则追加或替换内容
    256                 fw = new FileWriter(file, flag);
    257             }
    258         } catch (IOException e) {
    259             e.printStackTrace();
    260         }
    261         PrintWriter pw = new PrintWriter(fw);
    262         pw.println(content);
    263         pw.flush();
    264         try {
    265             fw.flush();
    266             pw.close();
    267             fw.close();
    268         } catch (IOException e) {
    269             e.printStackTrace();
    270         }
    271         return filedo;
    272     }
    273 
    274     /**
    275      * 写文件
    276      * @param ins
    277      * @param out
    278      */
    279     public static void writeIntoOut(InputStream ins, OutputStream out) {
    280         byte[] bb = new byte[10 * 1024];
    281         try {
    282             int cnt = ins.read(bb);
    283             while (cnt > 0) {
    284                 out.write(bb, 0, cnt);
    285                 cnt = ins.read(bb);
    286             }
    287         } catch (IOException e) {
    288             e.printStackTrace();
    289         } finally {
    290             try {
    291                 out.flush();
    292                 ins.close();
    293                 out.close();
    294             } catch (IOException e) {
    295                 e.printStackTrace();
    296             }
    297         }
    298     }
    299 
    300     /**
    301      * 判断list中元素是否完全相同(完全相同返回true,否则返回false)
    302      * @param list
    303      * @return
    304      */
    305     private static boolean hasSame(List<? extends Object> list){
    306         if(null == list)
    307             return false;
    308         return 1 == new HashSet<Object>(list).size();
    309     }
    310 
    311     /**
    312      * 判断list中是否有重复元素(无重复返回true,否则返回false)
    313      * @param list
    314      * @return
    315      */
    316     private static boolean hasSame2(List<? extends Object> list){
    317         if(null == list)
    318             return false;
    319         return list.size() == new HashSet<Object>(list).size();
    320     }
    321 
    322     /**
    323      * 增加/减少天数
    324      * @param date
    325      * @param num
    326      * @return
    327      */
    328     public static Date DateAddOrSub(Date date, int num) {
    329         Calendar startDT = Calendar.getInstance();
    330         startDT.setTime(date);
    331         startDT.add(Calendar.DAY_OF_MONTH, num);
    332         return startDT.getTime();
    333     }
    334     //https://www.cnblogs.com/chenhuan001/p/6575053.html
    335     /**
    336      * 递归删除文件或者目录
    337      * @param file_path
    338      */
    339     public static void deleteEveryThing(String file_path) {
    340         try{
    341             File file=new File(file_path);
    342             if(!file.exists()){
    343                 return ;
    344             }
    345             if(file.isFile()){
    346                 file.delete();
    347             }else{
    348                 File[] files = file.listFiles();
    349                 for(int i=0;i<files.length;i++){
    350                     String root=files[i].getAbsolutePath();//得到子文件或文件夹的绝对路径
    351                     deleteEveryThing(root);
    352                 }
    353                 file.delete();
    354             }
    355         } catch(Exception e) {
    356             System.out.println("删除文件失败");
    357         }
    358     }
    359     /**
    360      * 创建目录
    361      * @param dir_path
    362      */
    363     public static void mkDir(String dir_path) {
    364         File myFolderPath = new File(dir_path);
    365         try {
    366             if (!myFolderPath.exists()) {
    367                 myFolderPath.mkdir();
    368             }
    369         } catch (Exception e) {
    370             System.out.println("新建目录操作出错");
    371             e.printStackTrace();
    372         }
    373     }
    374 
    375     //https://blog.csdn.net/lovoo/article/details/77899627
    376     /**
    377      * 判断指定的文件是否存在。
    378      *
    379      * @param fileName
    380      * @return
    381      */
    382     public static boolean isFileExist(String fileName) {
    383         return new File(fileName).isFile();
    384     }
    385 
    386     /* 得到文件后缀名
    387      *
    388      * @param fileName
    389      * @return
    390      */
    391     public static String getFileExt(String fileName) {
    392         int point = fileName.lastIndexOf('.');
    393         int length = fileName.length();
    394         if (point == -1 || point == length - 1) {
    395             return "";
    396         } else {
    397             return fileName.substring(point + 1, length);
    398         }
    399     }
    400 
    401     /**
    402      * 删除文件夹及其下面的子文件夹
    403      *
    404      * @param dir
    405      * @throws IOException
    406      */
    407     public static void deleteDir(File dir) throws IOException {
    408         if (dir.isFile())
    409             throw new IOException("IOException -> BadInputException: not a directory.");
    410         File[] files = dir.listFiles();
    411         if (files != null) {
    412             for (int i = 0; i < files.length; i++) {
    413                 File file = files[i];
    414                 if (file.isFile()) {
    415                     file.delete();
    416                 } else {
    417                     deleteDir(file);
    418                 }
    419             }
    420         }
    421         dir.delete();
    422     }
    423 
    424     /**
    425      * 复制文件
    426      *
    427      * @param src
    428      * @param dst
    429      * @throws Exception
    430      */
    431     public static void copy(File src, File dst) throws Exception {
    432         int BUFFER_SIZE = 4096;
    433         InputStream in = null;
    434         OutputStream out = null;
    435         try {
    436             in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
    437             out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
    438             byte[] buffer = new byte[BUFFER_SIZE];
    439             int len = 0;
    440             while ((len = in.read(buffer)) > 0) {
    441                 out.write(buffer, 0, len);
    442             }
    443         } catch (Exception e) {
    444             throw e;
    445         } finally {
    446             if (null != in) {
    447                 try {
    448                     in.close();
    449                 } catch (IOException e) {
    450                     e.printStackTrace();
    451                 }
    452                 in = null;
    453             }
    454             if (null != out) {
    455                 try {
    456                     out.close();
    457                 } catch (IOException e) {
    458                     e.printStackTrace();
    459                 }
    460                 out = null;
    461             }
    462         }
    463     }
    464 
    465 
    466 }
  • 相关阅读:
    java.net.BindException: Address already in use: bind
    修改Oracle 10g Express Edition默认的8080端口
    五虎
    easily add files to META-INF in NetBeans
    http://edu.makery.ch/
    JavaFX 2 Dialogs
    JavaFx版本植物大战僵尸
    CSS样式表——布局练习(制作360网页)
    CSS样式表
    CSS样式表——超链接样式
  • 原文地址:https://www.cnblogs.com/cxhfuujust/p/11137985.html
Copyright © 2011-2022 走看看