package com.chenyang.nse.bussiness.tools.io;

import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.tools.filesystem.UnknownFileStruTool;
import com.chenyang.nse.bussiness.tools.net.FtpTool;
import com.chenyang.nse.bussiness.tools.net.SFTPUtil;
import com.chenyang.nse.bussiness.tools.string.StringTool;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
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.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.net.ftp.FTPClient;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class FileTool {
   public static final String VSERSION_CHARSET = "GBK";

   public static String getConfigPath() {
      FileTool ft = new FileTool();
      return ft.getClassRoot() + File.separator + "config.properties";
   }

   public String getClassRoot() {
      File f = new File(this.getClass().getResource("/").getPath());
      String path = f.getPath();
      return path;
   }

   public String getClassPath() {
      File f = new File(this.getClass().getResource("").getPath());
      String path = f.getPath();
      return path;
   }

   public String getProjectPath() {
      File directory = new File("");
      String courseFile = null;

      try {
         courseFile = directory.getCanonicalPath();
         return courseFile;
      } catch (IOException e) {
         e.printStackTrace();
         return courseFile;
      }
   }

   public String getAllClassPath() {
      String path = System.getProperty("java.class.path");
      return path;
   }

   public static boolean isFileExit(String filePath) {
      boolean exit = false;
      File file = new File(filePath);
      exit = file.exists();
      return exit;
   }

   public static boolean createFile(String path) {
      try {
         File file = new File(path);
         return file.exists() ? true : file.createNewFile();
      } catch (IOException e) {
         e.printStackTrace();
         return false;
      }
   }

   public static void writeContentToFile(String path, String content) {
      fileDirsCreate(path);
      FileWriter writer = null;

      try {
         writer = new FileWriter(path, true);
         writer.write(content);
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         try {
            if (writer != null) {
               writer.close();
            }
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

   }

   public static void fileDirsCreate(String pathName) {
      String path = pathName.substring(0, pathName.lastIndexOf(File.separator));
      File file = new File(path);
      if (!file.exists()) {
         file.mkdirs();
      }

   }

   public static void checkAndCreateFile(String filePath) throws IOException {
      if (!isFileExit(filePath)) {
         createFile(filePath);
      }

   }

   public static void createFolder(String path) {
      File file = new File(path);
      if (!file.exists() && !file.isDirectory()) {
         file.mkdirs();
      }

   }

   public static void removeFile(String path) {
      File file = new File(path);
      if (file.isFile() && file.exists()) {
         file.delete();
      }

   }

   public static List<String> getRootDir() {
      File[] fs = File.listRoots();
      if (fs.length == 0) {
         return null;
      } else {
         List<String> list = null;

         for(File file : fs) {
            if (file.isDirectory()) {
               if (list == null) {
                  list = new ArrayList();
               }

               list.add(file.getPath());
            }
         }

         return list;
      }
   }

   public static List<String> getPathDir(String path) {
      if (null != path && !"".equals(path)) {
         File parent = new File(path);
         if (parent.exists() && !parent.isFile()) {
            File[] list = parent.listFiles();
            if (null != list && list.length != 0) {
               List<String> result = new ArrayList();

               for(File child : list) {
                  if (child.isDirectory()) {
                     result.add(child.getName());
                  }
               }

               return result;
            } else {
               return null;
            }
         } else {
            return null;
         }
      } else {
         return getRootDir();
      }
   }

   public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
      File srcFile = new File(srcFileName);
      if (srcFile.exists() && srcFile.isFile()) {
         File destFile = new File(destFileName);
         if (destFile.exists()) {
            if (overlay) {
               (new File(destFileName)).delete();
            }
         } else if (!destFile.getParentFile().exists() && !destFile.getParentFile().mkdirs()) {
            return false;
         }

         int byteread = 0;
         InputStream in = null;
         OutputStream out = null;

         boolean var9;
         try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];

            while((byteread = in.read(buffer)) != -1) {
               out.write(buffer, 0, byteread);
            }

            return true;
         } catch (Exception var19) {
            var9 = false;
         } finally {
            try {
               if (out != null) {
                  out.close();
               }

               if (in != null) {
                  in.close();
               }
            } catch (IOException e) {
               e.printStackTrace();
            }

         }

         return var9;
      } else {
         return false;
      }
   }

   public static void clearFileContent(String path) {
      try {
         File f = new File(path);
         if (f.exists() && f.isFile()) {
            FileWriter fw = new FileWriter(f);
            fw.write("");
            fw.close();
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static long getFileSize(String path) {
      FileChannel fc = null;

      long var4;
      try {
         File f = new File(path);
         if (!f.exists() || !f.isFile()) {
            return 0L;
         }

         FileInputStream fis = new FileInputStream(f);
         fc = fis.getChannel();
         var4 = fc.size();
      } catch (Exception var16) {
         return 0L;
      } finally {
         if (null != fc) {
            try {
               fc.close();
            } catch (IOException var15) {
            }
         }

      }

      return var4;
   }

   public static String getFormatFileSize(long size) {
      if (size == 0L) {
         return "";
      } else {
         double s = Double.valueOf(String.valueOf(size));
         s /= (double)1024.0F;
         String suffix = "KB";
         if (s > (double)1024.0F) {
            s /= (double)1024.0F;
            suffix = "M";
         }

         if (s > (double)1024.0F) {
            s /= (double)1024.0F;
            suffix = "G";
         }

         DecimalFormat df = new DecimalFormat("######0.00");
         String result = df.format(s);
         return result + suffix;
      }
   }

   public static Date getFileModifyTime(String path) {
      File f = new File(path);
      long time = f.lastModified();
      Date d = new Date(time);
      return d;
   }

   public static List<String> getPathFile(String path) {
      if (null != path && !"".equals(path)) {
         File parent = new File(path);
         if (parent.exists() && !parent.isFile()) {
            File[] list = parent.listFiles();
            if (list != null && list.length != 0) {
               List<String> result = new ArrayList();

               for(File child : list) {
                  if (child.isFile()) {
                     result.add(child.getName());
                  }
               }

               return result;
            } else {
               return null;
            }
         } else {
            return null;
         }
      } else {
         return null;
      }
   }

   public static List<String> getPathFile(String path, String substring) {
      if (null != path && !"".equals(path)) {
         File parent = new File(path);
         if (parent.exists() && !parent.isFile()) {
            File[] list = parent.listFiles();
            if (list != null && list.length != 0) {
               List<String> result = new ArrayList();

               for(File child : list) {
                  if (child.isFile()) {
                     if (substring != null && !"".equals(substring)) {
                        if (child.getName().toUpperCase().contains(substring.toUpperCase())) {
                           result.add(child.getName());
                        }
                     } else {
                        result.add(child.getName());
                     }
                  }
               }

               return result;
            } else {
               return null;
            }
         } else {
            return null;
         }
      } else {
         return null;
      }
   }

   public static List<String> ergodicstartstr(File f, List<String> resultFileName, String startstr) {
      File[] files = f.listFiles();
      if (files == null) {
         return resultFileName;
      } else {
         for(File fi : files) {
            if (fi.isDirectory()) {
               ergodicstartstr(fi, resultFileName, startstr);
            } else if (fi.getName().startsWith(startstr)) {
               resultFileName.add(fi.getPath());
            }
         }

         return resultFileName;
      }
   }

   public static List<String> ergodicendstr(File f, List<String> resultFileName, String endstr) {
      File[] files = f.listFiles();
      if (files == null) {
         return resultFileName;
      } else {
         for(File fi : files) {
            if (fi.isDirectory()) {
               ergodicendstr(fi, resultFileName, endstr);
            } else if (fi.getName().endsWith(endstr)) {
               resultFileName.add(fi.getPath());
            }
         }

         return resultFileName;
      }
   }

   public static List<String> ergodicmatch(File f, List<String> resultFileName, String str) {
      File[] files = f.listFiles();
      if (files == null) {
         return resultFileName;
      } else {
         for(File fi : files) {
            if (fi.isDirectory()) {
               ergodicmatch(fi, resultFileName, str);
            } else if (fi.getName().equalsIgnoreCase(str)) {
               resultFileName.add(fi.getPath());
            }
         }

         return resultFileName;
      }
   }

   public static List<String> ergodicreg(File f, List<String> resultFileName, String regstr) {
      File[] files = f.listFiles();
      if (files == null) {
         return resultFileName;
      } else {
         Pattern pattern = Pattern.compile(regstr);

         for(File fi : files) {
            if (fi.isDirectory()) {
               ergodicreg(fi, resultFileName, regstr);
            } else if (pattern.matcher(fi.getName()).matches()) {
               resultFileName.add(fi.getPath());
            }
         }

         return resultFileName;
      }
   }

   public static List<String> getFileTitle(Map<String, String> map) {
      new ArrayList();
      String path = (String)map.get("path");
      if (!isFileExit(path)) {
         return null;
      } else {
         FileInputStream file = null;
         InputStreamReader isr = null;
         BufferedReader reader = null;
         String titlestring = null;

         try {
            file = new FileInputStream(path);
            isr = new InputStreamReader(file, getFileCharCode(path));
            reader = new BufferedReader(isr);
            titlestring = reader.readLine();
            reader.close();
         } catch (IOException e) {
            e.printStackTrace();
         } finally {
            if (reader != null) {
               try {
                  reader.close();
               } catch (IOException var17) {
               }
            }

         }

         String splitertype = (String)map.get("splitertype");
         List title;
         if ("1".equals(splitertype)) {
            int byteLength = Integer.valueOf((String)map.get("byteLength"));
            title = StringTool.widthSpliter(titlestring, byteLength);
         } else {
            String ch = (String)map.get("spliter");
            title = StringTool.charSpliter(titlestring, ch);
            if (((String)map.get("series")).equals("1")) {
               Iterator<String> it = title.iterator();

               for(int i = 0; i < title.size(); ++i) {
                  String temp = (String)it.next();
                  if (temp == null || "".equals(temp)) {
                     it.remove();
                     --i;
                  }
               }
            }
         }

         return title;
      }
   }

   public static String getFileCharCode(String path) {
      if (!isFileExit(path)) {
         return null;
      } else {
         String code = "";

         try {
            InputStream inputStream = new FileInputStream(path);
            byte[] head = new byte[3];
            inputStream.read(head);
            code = "gb2312";
            if (head[0] == -1 && head[1] == -2) {
               code = "UTF-16";
            }

            if (head[0] == -2 && head[1] == -1) {
               code = "Unicode";
            }

            if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
               code = "UTF-8";
            }

            System.out.println(code);
         } catch (IOException e) {
            e.printStackTrace();
         }

         return code;
      }
   }

   public static int getFileDataCount(String filename) {
      int cnt = 0;
      LineNumberReader reader = null;

      try {
         reader = new LineNumberReader(new FileReader(filename));
         String lineRead = "";

         while(reader.readLine() != null) {
         }

         cnt = reader.getLineNumber();
      } catch (Exception ex) {
         cnt = -1;
         ex.printStackTrace();
      } finally {
         try {
            reader.close();
         } catch (Exception ex) {
            ex.printStackTrace();
         }

      }

      return cnt;
   }

   public static long getFileDataCountBuffered(String filename) {
      InputStream is = null;
      long count = 0L;

      try {
         is = new BufferedInputStream(new FileInputStream(filename));
         byte[] c = new byte[1024];
         int readChars = 0;

         while((readChars = is.read(c)) != -1) {
            for(int i = 0; i < readChars; ++i) {
               if (c[i] == 10) {
                  ++count;
               }
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            is.close();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

      return count;
   }

   public static String readAppointedLineNumber(String sourceFile, int lineNumber) throws IOException {
      FileReader in = new FileReader(sourceFile);
      LineNumberReader reader = new LineNumberReader(in);
      String s = null;
      reader.setLineNumber(20);
      System.out.println("当前行号：" + reader.getLineNumber());
      s = reader.readLine();
      System.out.println(s);
      System.out.println("读取之后行号：" + reader.getLineNumber());
      reader.close();
      in.close();
      return s;
   }

   public static List<String> readFileContent(String path, String code) {
      List<String> content = new ArrayList();
      Reader in = null;
      BufferedReader reader = null;

      try {
         in = new InputStreamReader(new FileInputStream(path), code);
         reader = new BufferedReader(in);
         String line = null;

         while((line = reader.readLine()) != null) {
            content.add(line);
         }

         in.close();
         reader.close();
      } catch (Exception e) {
         e.printStackTrace();
      }

      return content;
   }

   public static List<String> readNSFileContent(String path, String code) {
      List<String> content = new ArrayList();
      Reader in = null;
      BufferedReader reader = null;

      try {
         in = new InputStreamReader(new FileInputStream(path), code);
         reader = new BufferedReader(in);
         String line = null;

         while((line = reader.readLine()) != null) {
            line = UnknownFileStruTool.replaceSeparation(line, " ");
            content.add(line);
         }

         in.close();
         reader.close();
      } catch (Exception e) {
         e.printStackTrace();
      }

      return content;
   }

   public static StringBuffer readFileContent(String path) {
      StringBuffer content = new StringBuffer();
      Reader in = null;
      BufferedReader reader = null;

      try {
         in = new InputStreamReader(new FileInputStream(path));
         reader = new BufferedReader(in);
         String line = null;

         while((line = reader.readLine()) != null) {
            content.append(line);
         }

         in.close();
         reader.close();
      } catch (Exception e) {
         e.printStackTrace();
      }

      return content;
   }

   public static Map<String, List<String>> getFileDataByWidth(String path, int count, List<String> width, String code) {
      Map<String, List<String>> map = new HashMap();
      if (width.size() != 0 && (width.size() != 1 || !"".equals(width.get(0)))) {
         boolean fileexit = isFileExit(path);
         if (!fileexit) {
            return null;
         } else {
            int fileDataCount = getFileDataCount(path);
            if (count > fileDataCount) {
               count = fileDataCount;
            }

            if (count < 0) {
               return map;
            } else {
               boolean b = count * 2 > fileDataCount;
               Reader in = null;
               LineNumberReader reader = null;
               List<String> datademo = new ArrayList();
               if (fileDataCount <= count) {
                  datademo = readNSFileContent(path, code);
               } else {
                  try {
                     Reader var15 = new InputStreamReader(new FileInputStream(path), code);
                     reader = new LineNumberReader(var15);

                     for(int i = 0; i < fileDataCount && datademo.size() < count; ++i) {
                        String s = reader.readLine();
                        if (b) {
                           int skip = fileDataCount / (fileDataCount - count) + 1;
                           if ((i + 1) % skip != 0) {
                              datademo.add(s);
                           }
                        } else {
                           int interval = fileDataCount / count;
                           if ((i + 1) % interval == 0) {
                              datademo.add(s);
                           }
                        }
                     }
                  } catch (Exception e) {
                     e.printStackTrace();
                  }
               }

               List<List<String>> ll = StringTool.widthSpliter(datademo, width);

               for(int i = 0; i < ll.size(); ++i) {
                  map.put(String.valueOf(i + 1), ll.get(i));
               }

               return map;
            }
         }
      } else {
         return map;
      }
   }

   public static Map<String, List<String>> getNSFileDataByWidth(String path, int count, List<String> width, String code) {
      Map<String, List<String>> map = new HashMap();
      boolean fileexit = isFileExit(path);
      if (!fileexit) {
         return null;
      } else {
         int fileDataCount = getFileDataCount(path);
         if (count > fileDataCount) {
            count = fileDataCount;
         }

         if (count < 0) {
            return null;
         } else {
            boolean b = count * 2 > fileDataCount;
            Reader in = null;
            LineNumberReader reader = null;
            List<String> datademo = new ArrayList();
            if (fileDataCount <= count) {
               datademo = readNSFileContent(path, code);
            } else {
               try {
                  Reader var15 = new InputStreamReader(new FileInputStream(path), code);
                  reader = new LineNumberReader(var15);

                  for(int i = 0; i < fileDataCount && datademo.size() < count; ++i) {
                     String s = reader.readLine();
                     s = UnknownFileStruTool.replaceSeparation(s, "");
                     if (b) {
                        int skip = fileDataCount / (fileDataCount - count) + 1;
                        if ((i + 1) % skip != 0) {
                           datademo.add(s);
                        }
                     } else {
                        int interval = fileDataCount / count;
                        if ((i + 1) % interval == 0) {
                           datademo.add(s);
                        }
                     }
                  }
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            List<List<String>> ll = StringTool.widthSpliter(datademo, width);

            for(int i = 0; i < ll.size(); ++i) {
               map.put(String.valueOf(i + 1), ll.get(i));
            }

            return map;
         }
      }
   }

   public static Map<String, List<String>> getFTPFileDataByWidth(String ip, int port, String username, String password, String path, String filename, int count, List<String> width, String code) {
      Map<String, List<String>> map = new HashMap();
      boolean fileexit = FtpTool.isFileExist(ip, port, username, password, path, filename);
      if (!fileexit) {
         return map;
      } else {
         int fileDataCount = 0;

         try {
            fileDataCount = FtpTool.getDataCount(ip, port, username, password, path, filename);
         } catch (Exception e1) {
            e1.printStackTrace();
         }

         if (count > fileDataCount) {
            count = fileDataCount;
         }

         if (count < 0) {
            return map;
         } else {
            boolean b = count * 2 > fileDataCount;
            Reader in = null;
            LineNumberReader reader = null;
            List<String> datademo = new ArrayList();
            if (fileDataCount <= count) {
               try {
                  datademo = FtpTool.getData(ip, port, username, password, path, filename, code);
               } catch (Exception e) {
                  e.printStackTrace();
               }
            } else {
               try {
                  InputStream is = FtpTool.getDataInputStream(ip, port, username, password, path, filename, code);
                  Reader var23 = new InputStreamReader(is, code);
                  reader = new LineNumberReader(var23);

                  for(int i = 0; i < fileDataCount && datademo.size() < count; ++i) {
                     String s = reader.readLine();
                     if (b) {
                        int skip = fileDataCount / (fileDataCount - count) + 1;
                        if ((i + 1) % skip != 0) {
                           datademo.add(s);
                        }
                     } else {
                        int interval = fileDataCount / count;
                        if ((i + 1) % interval == 0) {
                           datademo.add(s);
                        }
                     }
                  }
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            List<List<String>> ll = StringTool.widthSpliter(datademo, width);

            for(int i = 0; i < ll.size(); ++i) {
               map.put(String.valueOf(i + 1), ll.get(i));
            }

            return map;
         }
      }
   }

   public static Map<String, List<String>> getFTPFileDataByWidth(FTPClient ftp, String path, String filename, int count, List<String> width, String code) {
      Map<String, List<String>> map = new HashMap();
      boolean fileexit = FtpTool.isFileExist(ftp, path, filename);
      if (!fileexit) {
         return map;
      } else {
         int fileDataCount = 0;

         try {
            fileDataCount = FtpTool.getDataCount(ftp, path, filename);
         } catch (Exception e1) {
            e1.printStackTrace();
         }

         if (count > fileDataCount) {
            count = fileDataCount;
         }

         if (count < 0) {
            return map;
         } else {
            boolean b = count * 2 > fileDataCount;
            Reader in = null;
            LineNumberReader reader = null;
            List<String> datademo = new ArrayList();
            InputStream is = null;

            try {
               if (fileDataCount <= count) {
                  datademo = FtpTool.getData(ftp, path, filename, code);
               } else {
                  is = FtpTool.getDataInputStream(ftp, path, filename, code);
                  in = new InputStreamReader(is, code);
                  reader = new LineNumberReader(in);

                  for(int i = 0; i < fileDataCount && datademo.size() < count; ++i) {
                     String s = reader.readLine();
                     if (b) {
                        int skip = fileDataCount / (fileDataCount - count) + 1;
                        if ((i + 1) % skip != 0) {
                           datademo.add(s);
                        }
                     } else {
                        int interval = fileDataCount / count;
                        if ((i + 1) % interval == 0) {
                           datademo.add(s);
                        }
                     }
                  }
               }

               List<List<String>> ll = StringTool.widthSpliter(datademo, width);

               for(int i = 0; i < ll.size(); ++i) {
                  map.put(String.valueOf(i + 1), ll.get(i));
               }
            } catch (Exception e1) {
               e1.printStackTrace();
            } finally {
               try {
                  if (reader != null) {
                     reader.close();
                  }

                  if (in != null) {
                     in.close();
                  }

                  if (is != null) {
                     is.close();
                     ftp.completePendingCommand();
                  }
               } catch (IOException e) {
                  e.printStackTrace();
               }

            }

            return map;
         }
      }
   }

   public static Map<String, List<String>> getSFTPFileDataByWidth(SFTPUtil sftp, String path, String filename, int count, List<String> width, String code) {
      Map<String, List<String>> map = new HashMap();
      boolean fileexit = sftp.isExitFile(path + filename);
      if (!fileexit) {
         return null;
      } else if (width.size() == 1 && "".equals(width.get(0))) {
         return map;
      } else {
         int fileDataCount = 0;

         try {
            fileDataCount = sftp.getDataCount(path + filename);
         } catch (Exception e1) {
            e1.printStackTrace();
         }

         if (count > fileDataCount) {
            count = fileDataCount;
         }

         if (count < 0) {
            return null;
         } else {
            boolean b = count * 2 > fileDataCount;
            Reader in = null;
            LineNumberReader reader = null;
            InputStream is = null;
            List<String> datademo = new ArrayList();
            if (fileDataCount <= count) {
               try {
                  datademo = sftp.getData(path + filename, code);
               } catch (Exception e) {
                  e.printStackTrace();
               }
            } else {
               try {
                  is = sftp.getDataInputStream(path + filename);
                  in = new InputStreamReader(is, code);
                  reader = new LineNumberReader(in);

                  for(int i = 0; i < fileDataCount && datademo.size() < count; ++i) {
                     String s = reader.readLine();
                     if (b) {
                        int skip = fileDataCount / (fileDataCount - count) + 1;
                        if ((i + 1) % skip != 0) {
                           datademo.add(s);
                        }
                     } else {
                        int interval = fileDataCount / count;
                        if ((i + 1) % interval == 0) {
                           datademo.add(s);
                        }
                     }
                  }
               } catch (Exception e) {
                  e.printStackTrace();
               } finally {
                  if (reader != null) {
                     try {
                        reader.close();
                     } catch (IOException e) {
                        e.printStackTrace();
                     }
                  }

                  if (in != null) {
                     try {
                        in.close();
                     } catch (IOException e) {
                        e.printStackTrace();
                     }
                  }

                  if (is != null) {
                     try {
                        is.close();
                     } catch (IOException e) {
                        e.printStackTrace();
                     }
                  }

               }
            }

            List<List<String>> ll = StringTool.widthSpliter(datademo, width);

            for(int i = 0; i < ll.size(); ++i) {
               map.put(String.valueOf(i + 1), ll.get(i));
            }

            return map;
         }
      }
   }

   public static Map<String, List<String>> getFileDataBySpliter(String path, int count, String spliter, String quotecharacter, String code, int num) throws Exception {
      Map<String, List<String>> map = new HashMap();
      boolean fileexit = isFileExit(path);
      if (!fileexit) {
         return null;
      } else {
         int fileDataCount = getFileDataCount(path);
         if (count > fileDataCount) {
            count = fileDataCount;
         }

         if (count < 0) {
            return null;
         } else {
            boolean b = count * 2 > fileDataCount;
            Reader in = null;
            BufferedReader reader = null;
            List<String> datademo = new ArrayList();
            if (fileDataCount <= count) {
               datademo = readFileContent(path, code);
            } else {
               try {
                  in = new InputStreamReader(new FileInputStream(path), code);
                  reader = new BufferedReader(in);

                  for(int i = 0; i < count; ++i) {
                     String s = reader.readLine();
                     datademo.add(s);
                  }

                  in.close();
                  reader.close();
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            List<List<String>> ll = StringTool.splitString(datademo, spliter, num, quotecharacter);

            for(int i = 0; i < ll.size(); ++i) {
               map.put(String.valueOf(i + 1), ll.get(i));
            }

            return map;
         }
      }
   }

   public static Map<String, List<String>> getFTPFileDataBySpliter(String ip, Integer port, String username, String password, String path, String filename, int count, String spliter, String quotecharacter, String code, int num) throws Exception {
      Map<String, List<String>> map = new HashMap();
      boolean fileexit = FtpTool.isFileExist(ip, port, username, password, path, filename);
      if (!fileexit) {
         return null;
      } else {
         int fileDataCount = 0;

         try {
            fileDataCount = FtpTool.getDataCount(ip, port, username, password, path, filename);
         } catch (Exception e1) {
            e1.printStackTrace();
         }

         if (count > fileDataCount) {
            count = fileDataCount;
         }

         if (count < 0) {
            return null;
         } else {
            boolean b = count * 2 > fileDataCount;
            Reader in = null;
            BufferedReader reader = null;
            List<String> datademo = new ArrayList();
            if (fileDataCount <= count) {
               try {
                  datademo = FtpTool.getData(ip, port, username, password, path, filename, code);
               } catch (Exception e) {
                  e.printStackTrace();
               }
            } else {
               try {
                  InputStream is = FtpTool.getDataInputStream(ip, port, username, password, path, filename, code);
                  in = new InputStreamReader(is, code);
                  reader = new BufferedReader(in);

                  for(int i = 0; i < count; ++i) {
                     String s = reader.readLine();
                     datademo.add(s);
                  }

                  reader.close();
                  in.close();
                  is.close();
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            List<List<String>> ll = StringTool.splitString(datademo, spliter, num, quotecharacter);

            for(int i = 0; i < ll.size(); ++i) {
               map.put(String.valueOf(i + 1), ll.get(i));
            }

            return map;
         }
      }
   }

   public static Map<String, List<String>> getSFTPFileDataBySpliter(SFTPUtil sftp, String path, String filename, int count, String spliter, String code, int num) {
      Map<String, List<String>> map = new HashMap();
      boolean fileexit = sftp.isExitFile(path + filename);
      if (!fileexit) {
         return null;
      } else {
         int fileDataCount = 0;

         try {
            fileDataCount = sftp.getDataCount(path + filename);
         } catch (Exception e1) {
            e1.printStackTrace();
         }

         if (count > fileDataCount) {
            count = fileDataCount;
         }

         if (count < 0) {
            return null;
         } else {
            boolean b = count * 2 > fileDataCount;
            Reader in = null;
            BufferedReader reader = null;
            List<String> datademo = new ArrayList();
            if (fileDataCount <= count) {
               try {
                  datademo = sftp.getData(path + filename, code);
               } catch (Exception e) {
                  e.printStackTrace();
               }
            } else {
               try {
                  InputStream is = sftp.getDataInputStream(path + filename);
                  in = new InputStreamReader(is, code);
                  reader = new BufferedReader(in);

                  for(int i = 0; i < count; ++i) {
                     String s = reader.readLine();
                     datademo.add(s);
                  }

                  reader.close();
                  in.close();
                  is.close();
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            List<List<String>> ll = StringTool.splitString(datademo, spliter, num);

            for(int i = 0; i < ll.size(); ++i) {
               map.put(String.valueOf(i + 1), ll.get(i));
            }

            return map;
         }
      }
   }

   public static Map<String, List<String>> getSFTPFileDataBySpliterandSkiprows(SFTPUtil sftp, String path, String filename, int count, String spliter, String quotecharacter, String code, int num, String skiprows) throws Exception {
      Map<String, List<String>> map = new HashMap();
      boolean fileexit = sftp.isExitFile(path + filename);
      if (!fileexit) {
         return null;
      } else {
         int fileDataCount = 0;

         try {
            fileDataCount = sftp.getDataCount(path + filename) - Integer.parseInt(skiprows);
         } catch (Exception e1) {
            e1.printStackTrace();
         }

         if (count > fileDataCount) {
            count = fileDataCount;
         }

         if (count < 0) {
            return null;
         } else {
            boolean b = count * 2 > fileDataCount;
            Reader in = null;
            BufferedReader reader = null;
            List<String> datademo = new ArrayList();
            if (fileDataCount <= count) {
               try {
                  datademo = sftp.getDataBySkiprows(path + filename, skiprows, code);
               } catch (Exception e) {
                  e.printStackTrace();
               }
            } else {
               try {
                  InputStream is = sftp.getDataInputStream(path + filename);
                  in = new InputStreamReader(is, code);
                  reader = new BufferedReader(in);

                  for(int i = 0; i < count; ++i) {
                     String s = reader.readLine();
                     datademo.add(s);
                  }

                  reader.close();
                  in.close();
                  is.close();
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }

            List<List<String>> ll = StringTool.splitString(datademo, spliter, num, quotecharacter);

            for(int i = 0; i < ll.size(); ++i) {
               map.put(String.valueOf(i + 1), ll.get(i));
            }

            return map;
         }
      }
   }

   public static void getFileList(File f, List<File> list) {
      List<File> l = list;
      if (f != null) {
         if (f.isDirectory()) {
            File[] fileArray = f.listFiles();
            if (fileArray != null) {
               for(int i = 0; i < fileArray.length; ++i) {
                  getFileList(fileArray[i], l);
               }
            }
         } else {
            list.add(f);
         }
      }

   }

   public static List<File> getFileList(String path) {
      List<File> list = new ArrayList();
      getFileList(new File(path), list);
      return list;
   }

   public static List<HashMap> errorlog() {
      new HashMap();
      List<HashMap> listmap = new ArrayList();
      List<String> datademo = readFileContent("c:\\abc\\l402882e55d4f4ff0015d4f511e730000.bad", "utf-8");

      for(int i = 0; i < datademo.size(); ++i) {
         HashMap map = new HashMap();
         String[] a = ((String)datademo.get(i)).split(",");
         int num = 0;

         for(int j = 0; j < a.length; ++j) {
            if (!a[j].equals("D")) {
               ++num;
               map.put(num, a[j]);
            }
         }

         listmap.add(map);
      }

      return listmap;
   }

   public static void PrintToFile(String path, String... value) {
      try {
         PrintStream printStream = new PrintStream(new FileOutputStream(path));
         PrintStream oldStream = System.err;
         System.setErr(printStream);

         for(int i = 0; i < value.length; ++i) {
            System.err.println(value[i]);
         }

         oldStream.flush();
         oldStream.flush();
         oldStream.close();
         printStream.close();
      } catch (Exception var5) {
      }

   }

   public static String fileRead(String path) {
      File file = new File(path);
      String str = "";

      try {
         FileReader reader = new FileReader(file);
         BufferedReader bReader = new BufferedReader(reader);
         StringBuilder sb = new StringBuilder();
         String s = "";

         while((s = bReader.readLine()) != null) {
            sb.append(s + "\n");
         }

         bReader.close();
         str = sb.toString();
      } catch (Exception e) {
         System.out.println(e.toString());
      }

      return str;
   }

   public static String fileCodeToPowercenterCode(String fileCode) {
      if ("UTF-8".equalsIgnoreCase(fileCode)) {
         fileCode = "utf-8";
      } else if ("ASCII".equalsIgnoreCase(fileCode)) {
         fileCode = "us-ascii";
      } else if ("Unicode".equalsIgnoreCase(fileCode)) {
         fileCode = "utf-16le";
      } else if ("Unicode big endian".equalsIgnoreCase(fileCode)) {
         fileCode = "utf-16be";
      }

      return fileCode;
   }

   public static int stringCount(String str, String ss) {
      int sc;
      for(sc = 0; str.indexOf(ss) != -1; ++sc) {
         str = str.substring(str.indexOf(ss) + 1, str.length());
      }

      return sc;
   }

   public static void modifyOraFile(boolean isDelete, String filePath, TCoreDatasystem datasource) {
      try {
         File file = new File(filePath);
         String writeTxt = "";
         if (file.isFile() && file.exists()) {
            InputStreamReader read = new InputStreamReader(new FileInputStream(file), "GBK");
            BufferedReader br = new BufferedReader(read);
            String lineTxt = null;
            boolean isWrite = true;
            int pnNum = 0;
            boolean isNextLine = false;

            while((lineTxt = br.readLine()) != null) {
               if (lineTxt.length() > 0 && !lineTxt.substring(0, 1).equals("#")) {
                  int lCount = stringCount(lineTxt, "(");
                  int rCount = stringCount(lineTxt, ")");
                  if (lCount == 0 && rCount == 0 && lineTxt.replace(" ", "").replace("=", "").equals(datasource.getDblinkname())) {
                     isWrite = false;
                  }

                  if (isWrite) {
                     writeTxt = writeTxt + lineTxt + "\n";
                  } else if (isNextLine) {
                     pnNum = pnNum + lCount - rCount;
                     if (pnNum == 0) {
                        isWrite = true;
                        isNextLine = false;
                     }
                  } else {
                     isNextLine = true;
                  }
               } else {
                  writeTxt = writeTxt + lineTxt + "\n";
               }
            }

            read.close();
            if (!isDelete) {
               String appendTxt = datasource.getDblinkname() + " =\n  (DESCRIPTION =\n    (ADDRESS = (PROTOCOL = TCP)(HOST = " + datasource.getDbip() + ")(PORT = " + datasource.getDbport() + "))\n    (CONNECT_DATA =\n      (SERVER = DEDICATED)\n      (SERVICE_NAME = " + datasource.getDbservername() + ")\n    )\n  )";
               writeTxt = writeTxt + appendTxt;
            }
         }

         clearFileContent(filePath);
         writeContentToFile(filePath, writeTxt);
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public static void modifyIniFile(boolean isDelete, String filePath, TCoreDatasystem datasource, String linkname, String infaHome) {
      try {
         String content = fileRead(filePath);
         if (!StringTool.emptyOrNull(datasource.getId()) & (datasource.getDbtype().equals("ORACLE") || datasource.getDbtype().equals("DB2") || datasource.getDbtype().equals("MSSQLSERVER") || datasource.getDbtype().equals("MYSQL") || datasource.getDbtype().equals("SYBASE_IQ") || datasource.getDbtype().equals("MARIADB") || datasource.getDbtype().equals("GREENPLUM") || datasource.getDbtype().equals("SYBASE") || datasource.getDbtype().equals("INFORMIX")) && content.contains("[" + linkname + "]")) {
            System.out.println("包含linkname," + linkname);
            int startindex = content.indexOf("[" + linkname + "]");
            String upPart = content.substring(0, startindex);
            int endindex = content.substring(startindex + ("[" + linkname + "]").length(), content.length()).contains("[") ? content.substring(startindex + ("[" + linkname + "]").length(), content.length()).indexOf("[") + upPart.length() + ("[" + linkname + "]").length() : content.length();
            String downPart = content.substring(endindex, content.length());
            content = upPart + downPart;
         }

         String odbclink = "";
         if (!isDelete) {
            if (datasource.getDbtype().equals("ORACLE")) {
               odbclink = "[" + datasource.getDblinkname() + "] \nDriver=" + infaHome + "/ODBC7.1/lib/DWora27.so\nDescription=DataDirect 7.1 Oracle Wire Protocol\nHostName=" + datasource.getDbip() + "\nServerType=oracle\nPortNumber=" + datasource.getDbport() + "\nSID=" + datasource.getDbservername() + "\nUser=\nPassword=\nDatabase=\nMETADATA_ID=0\n";
               if (datasource.getPagecode().equals("GBK")) {
                  odbclink = odbclink + "IANAAPPCODEPAGE=113\n";
               } else {
                  odbclink = odbclink + "IANAAPPCODEPAGE=106\n";
               }
            } else if (datasource.getDbtype().equals("DB2")) {
               odbclink = "[" + datasource.getDblinkname() + "] \nDriver=" + infaHome + "/ODBC7.1/lib/DWdb227.so\nDescription=DataDirect 7.1 DB2 Wire Protocol\nAccountingInfo=\nAddStringToCreateTable=\nAlternateID=\nAlternateServers=\nApplicationName=\nApplicationUsingThreads=1\nAuthenticationMethod=0\nBulkBinaryThreshold=32\nBulkCharacterThreshold=-1\nBulkLoadBatchSize=1024\nBulkLoadFieldDelimiter=\nBulkLoadRecordDelimiter=\nCatalogSchema=\nCharsetFor65535=0\nClientHostName=\nClientUser=\nCollection=\nConcurrentAccessResolution=0\nConnectionReset=0\nConnectionRetryCount=0\nConnectionRetryDelay=3\nCurrentFuncPath=\nDatabase=" + datasource.getDbservername() + "\nDefaultIsolationLevel=1\nDynamicSections=1000\nEnableBulkLoad=0\nEncryptionMethod=0\nFailoverGranularity=0\nFailoverMode=0\nFailoverPreconnect=0\nGrantAuthid=PUBLIC\nGrantExecute=1\nGSSClient=native\nHostNameInCertificate=\nIpAddress=" + datasource.getDbip() + "\nKeyPassword=\nKeyStore=\nKeyStorePassword=\nLoadBalanceTimeout=0\nLoadBalancing=0\nLocation=\nLogonID=" + datasource.getUsername() + "\nMaxPoolSize=100\nMinPoolSize=0\nPassword=" + datasource.getPassword() + "\nPackageCollection=\nPackageNamePrefix=\nPackageOwner=\nPooling=0\nProgramID=\nQueryTimeout=0\nReportCodePageConversionErrors=0\nTcpPort=" + datasource.getDbport() + "\nTrustStore=\nTrustStorePassword=\nUseCurrentSchema=0\nValidateServerCertificate=1\nWithHold=1\n";
               if (datasource.getPagecode().equals("GBK")) {
                  odbclink = odbclink + "IANAAPPCODEPAGE=113\nDB2CODEPAGE=1386";
               } else {
                  odbclink = odbclink + "IANAAPPCODEPAGE=106\nDB2CODEPAGE=1208";
               }
            } else if (datasource.getDbtype().equals("MSSQLSERVER")) {
               odbclink = "[" + datasource.getDblinkname() + "] \nDriver=" + infaHome + "/ODBC7.1/lib/DWsqls27.so\nDescription=DataDirect 7.0 SQL Server Wire Protocol\nAlwaysReportTriggerResults=0\nAnsiNPW=1\nApplicationUsingThreads=1\nConnectionRetryDelay=3\nDatabase=" + datasource.getDbservername() + "\nFetchTWFSasTime=1\nGSSClient=native\nHostName=" + datasource.getDbip() + "\nLoginTimeout=15\nLogonID=" + datasource.getUsername() + "\nMaxPoolSize=100\nMinPoolSize=0\nPacketSize=-1\nPassword=" + datasource.getPassword() + "\nPortNumber=" + datasource.getDbport() + "\nValidateServerCertificate=1\nXMLDescribeType=-10\nEnableQuotedIdentifiers=1\n";
               if (datasource.getPagecode().equals("GBK")) {
                  odbclink = odbclink + "IANAAPPCODEPAGE=113";
               } else {
                  odbclink = odbclink + "IANAAPPCODEPAGE=106";
               }
            } else if (!datasource.getDbtype().equals("MYSQL") && !datasource.getDbtype().equals("MARIADB")) {
               if (datasource.getDbtype().equals("SYBASE_IQ")) {
                  odbclink = "[" + datasource.getDblinkname() + "]\nDriver=" + infaHome + "/ODBC7.1/lib/ddsyiq27.so\nDescription=DataDirect 7.1 Sybase IQ Wire Protocol\nDatabase=" + datasource.getDbservername() + "\nLogonID=" + datasource.getUsername() + "\nPassword=" + datasource.getPassword() + "\nNetworkAddress=" + datasource.getDbip() + "," + datasource.getDbport() + "\n";
                  if (datasource.getPagecode().equals("GBK")) {
                     odbclink = odbclink + "Charset=GBK\n";
                  } else {
                     odbclink = odbclink + "Charset=UTF8\n";
                  }
               } else if (datasource.getDbtype().equals("INFORMIX")) {
                  odbclink = "[" + datasource.getDblinkname() + "]\nDriver=" + infaHome + "/ODBC7.1/lib/DWifcl27.so\nDescription=DataDirect 7.1 Informix Wire Protocol\nAlternateServers=\nApplicationUsingThreads=1\nCancelDetectInterval=0\nConnectionRetryCount=0\nConnectionRetryDelay=3\nDatabase=" + datasource.getDbservername() + "\nHostName=" + datasource.getDbip() + "\nLoadBalancing=0\nLogonID=" + datasource.getUsername() + "\nPassword=" + datasource.getPassword() + "\nPortNumber=" + datasource.getDbport() + "\nServerName=" + datasource.getServername() + "\nTrimBlankFromIndexName=1\nUseDelimitedIdentifiers=0\n";
                  if (datasource.getPagecode().equals("GBK")) {
                     odbclink = odbclink + "Charset=GBK\n";
                  } else {
                     odbclink = odbclink + "Charset=UTF8\n";
                  }
               } else if (datasource.getDbtype().equals("SYBASE")) {
                  odbclink = "[" + datasource.getDblinkname() + "]\nDriver=" + infaHome + "/ODBC7.1/lib/DWase27.so\nDescription=DataDirect 7.1 Sybase Wire Protocol\nAlternateServers=\nApplicationName=\nApplicationUsingThreads=1\nArraySize=50\nAuthenticationMethod=0\nBulkBinaryThreshold=32\nBulkCharacterThreshold=-1\nBulkLoadBatchSize=1024\nBulkLoadFieldDelimiter=\nBulkLoadRecordDelimiter=\nConnectionReset=0\nConnectionRetryCount=0\nConnectionRetryDelay=3\nCursorCacheSize=1\nDatabase=" + datasource.getDbservername() + "\nDefaultLongDataBuffLen=1024\nEnableBulkLoad=0\nEnableDescribeParam=0\nEnableQuotedIdentifiers=0\nEncryptionMethod=0\nFailoverGranularity=0\nFailoverMode=0\nFailoverPreconnect=0\nGSSClient=native\nHostNameInCertificate=\nInitializationString=\nLanguage=\nLoadBalancing=0\nLoadBalanceTimeout=0\nLoginTimeout=15\nLogonID=" + datasource.getUsername() + "\nMaxPoolSize=100\nMinPoolSize=0\nNetworkAddress=" + datasource.getDbip() + "," + datasource.getDbport() + "\nOptimizePrepare=1\nPacketSize=0\nPassword=" + datasource.getPassword() + "\nPooling=0\nQueryTimeout=0\nRaiseErrorPositionBehavior=0\nReportCodePageConversionErrors=0\nSelectMethod=0\nServicePrincipalName=\nTruncateTimeTypeFractions=0\nTrustStore=\nTrustStorePassword=\nValidateServerCertificate=1\nWorkStationID=\n";
                  if (datasource.getPagecode().equals("GBK")) {
                     odbclink = odbclink + "IANAAppCodePage=113";
                  } else {
                     odbclink = odbclink + "IANAAppCodePage=106";
                  }
               } else if (datasource.getDbtype().equals("GREENPLUM")) {
                  odbclink = "[" + datasource.getDblinkname() + "]\nDriver=" + infaHome + "/ODBC7.1/lib/DWgplm27.so\nDescription=DataDirect 7.1 Greenplum Wire Protocol\nDatabase=" + datasource.getDbservername() + "\nHostName=" + datasource.getDbip() + "\nLogonID=" + datasource.getUsername() + "\nPassword=" + datasource.getPassword() + "\nPortNumber=" + datasource.getDbport() + "\nXMLDescribeType=-10\n";
                  if (datasource.getPagecode().equals("GBK")) {
                     odbclink = odbclink + "Charset=GBK\n";
                  } else {
                     odbclink = odbclink + "Charset=UTF8\n";
                  }
               }
            } else {
               odbclink = "[" + datasource.getDblinkname() + "]\nDriver=" + infaHome + "/ODBC7.1/lib/libmyodbc5w.so\nSERVER=" + datasource.getDbip() + "\nPORT=" + datasource.getDbport() + "\nUSER=" + datasource.getUsername() + "\nPassword=" + datasource.getPassword() + "\nDatabase=" + datasource.getDbservername() + "\nOPTION=30\nSOCKET=\nprefetch=50000\nDriverUnicodeType=1\n";
               if (datasource.getPagecode().equals("GBK")) {
                  odbclink = odbclink + "CHARSET= GBK\n";
               } else {
                  odbclink = odbclink + "CHARSET= UTF8\n";
               }
            }
         }

         clearFileContent(filePath);
         String newcontent = content + odbclink;
         writeContentToFile(filePath, newcontent);
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public static String htmlTM(String path) {
      return "";
   }

   public static boolean delAllFile(String path) {
      boolean flag = false;
      File file = new File(path);
      if (!file.exists()) {
         return flag;
      } else if (!file.isDirectory()) {
         return flag;
      } else {
         String[] tempList = file.list();
         File temp = null;

         for(int i = 0; i < tempList.length; ++i) {
            if (path.endsWith(File.separator)) {
               temp = new File(path + tempList[i]);
            } else {
               temp = new File(path + File.separator + tempList[i]);
            }

            if (temp.isFile()) {
               temp.delete();
            }

            if (temp.isDirectory()) {
               delAllFile(path + "/" + tempList[i]);
               delFolder(path + "/" + tempList[i]);
               flag = true;
            }
         }

         return flag;
      }
   }

   public static void delFolder(String folderPath) {
      try {
         delAllFile(folderPath);
         String e = folderPath.toString();
         File myFilePath = new File(e);
         myFilePath.delete();
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public static void updateProperties(String key, String value) throws IOException {
      String path = (new FileTool()).getClassRoot() + File.separator + "config.properties";
      BufferedReader bufReader = null;
      bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path))));
      StringBuffer strBuffer = new StringBuffer();

      String temp;
      for(temp = null; (temp = bufReader.readLine()) != null; temp = null) {
         if (temp.trim().indexOf(key) == 0) {
            temp = key + "=" + value;
         }

         strBuffer.append(temp);
         strBuffer.append(System.getProperty("line.separator"));
      }

      bufReader.close();
      PrintWriter printWriter = new PrintWriter(path);
      printWriter.write(strBuffer.toString().toCharArray());
      printWriter.flush();
      printWriter.close();
   }

   public static void updateXml(String xml_node, String value) throws DocumentException, IOException {
      String str = null;
      String path = (new FileTool()).getClassRoot() + File.separator + "filebase.xml";

      try {
         SAXReader reader = new SAXReader();
         Element root = reader.read(new File(path)).getDocument().getRootElement();
         List<Node> list = root.selectNodes(xml_node);
         if (list != null) {
            ((Node)list.get(0)).setText(value);
         }

         FileOutputStream out = new FileOutputStream(path);
         XMLWriter writer = new XMLWriter(out);
         writer.write(root);
         System.out.println(path);
      } catch (DocumentException e) {
         e.printStackTrace();
      }

   }

   public static void main(String[] args) throws DocumentException, IOException {
   }
}
