java讀取本地文件備份並解析入庫


//從配置文件中獲取文件路徑
String filePath = Global.getConfig("filePath", "log-resolve.properties");
String copyFilePath = Global.getConfig("copyFilePath", "log-resolve.properties");
try {
String encoding = "utf-8";
File file = new File(filePath);
//判斷文件是否存在
if(file.isFile()&&file.exists()){
    //step1 備份文件,清理原文件
    copyFile(filePath, copyFilePath);
    FileWriter fw = new FileWriter(file);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write("");
    bw.close();
    //step2 讀取備份文件,並解析入庫
    File fileCopy = new File(copyFilePath);
    InputStreamReader read = new InputStreamReader(new FileInputStream(fileCopy),encoding);
    BufferedReader bufferedReader = new BufferedReader(read);
    String lineTxt = "";
    while((lineTxt=bufferedReader.readLine())!=null){
        System.out.println(lineTxt);
        //截取字符串
        //截取文件編號
        String fileNumber = lineTxt.substring(0, lineTxt.indexOf(" "));
        //截取開始時間
        String str = lineTxt.substring(0, lineTxt.lastIndexOf(" ")-1);
        String startTime = str.substring(str.lastIndexOf(" ")+1);
        //截取文件名
        String fileName = str.substring(str.indexOf(" ")+2, str.lastIndexOf(" ")-1);
        //截取結束時間
        String endTime = lineTxt.substring(lineTxt.lastIndexOf(" ")+1);
        OneWayRunLog oneWayRunLog = new OneWayRunLog();
        oneWayRunLog.setFileNumber(fileNumber);
        oneWayRunLog.setFileName(fileName);
        oneWayRunLog.setStartTime(startTime);
        oneWayRunLog.setEndTime(endTime);
        oneWayRunLogService.save(oneWayRunLog);
    }
    read.close();
}else{
    System.out.println("找不到指定的文件");
}


/**
 * 文件備份
 * */
public static int copyFile(String src, String dst) {
    try {
      int len = 0;
      byte[] buf = new byte[1024];
      FileInputStream fis = new FileInputStream(src);
      FileOutputStream fos = new FileOutputStream(dst);
      while ( (len = fis.read(buf)) != -1) {
        fos.write(buf, 0, len);
      }
      fis.close();
      fos.close();
    }
    catch (IOException e) {
      System.out.println(e);
      return -1;
    }
    return 0;
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM