通过存储过程调用java 代码,进行解压和读取文件从而更新数据表信息

通过存储过程调用java 代码,进行解压ZIP和读取文件从而更新数据表信息

解压zip文件的java代码

package com.abc;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @Description 解压缩文件工具类
 * @Author xuelin
 * @Date 2021/9/13
 * @Version 1.0.0
 */
public class ZipUtils {

    /**
     *   解压文件
     * @param zipFilePath 压缩文件的绝对路径,例如:C:/zipFileName.zip
     * @param deCompressionPath 解压文件存放的路径,例如:C:/dir/
     * @param readEncoding 解压时读出的文件编码格式,例如:GBK
     */
    public void decompressionFile(String zipFilePath, String deCompressionPath, String readEncoding) {
        FileOutputStream fos = null;
        InputStream is = null;
        ZipFile zipFileItems = null;
        try {
            //  以指定格式打开zip文件
            zipFileItems = new ZipFile(zipFilePath , Charset.forName(readEncoding));
            //  获取zip文件的条目
            Enumeration<? extends ZipEntry> items = zipFileItems.entries();
            while(items.hasMoreElements()) {
                //  压缩文件中当前的所操作文件或文件夹的对象
                ZipEntry zipCurrentItem = items.nextElement();
                if(zipCurrentItem.isDirectory()) {//  遇到文件夹时深入文件夹递归
                    File newFile = new File(deCompressionPath+zipCurrentItem.getName());
                    if(!newFile.exists()) {
                        newFile.mkdirs();
                    }
                }else {
                    //  获取当前条目文件的输入流
                    is = zipFileItems.getInputStream(zipCurrentItem);
                    byte[] b = new byte[1024];
                    File newFile = new File(deCompressionPath+zipCurrentItem.getName());
                    if(!newFile.exists()) {
                        new File(deCompressionPath).mkdirs();// 创建路径
                        newFile.createNewFile();
                    }
                    fos = new FileOutputStream(newFile);
                    int len;
                    while((len = is.read(b)) != -1) {
                        fos.write(b, 0, len);
                    }
                    System.out.println("解压文件 : "+zipCurrentItem.getName()+" 完成!");
                }
            }
            zipFileItems.close();
        }catch (FileNotFoundException e) {
            System.err.println("你输入的文件路径有误,请检查文件路径及其后缀是否正确!");
        } catch (IOException e) {
            System.out.println("文件流异常断开!");
        } finally {
            closeAll(fos,is,zipFileItems,null,null);
        }
    }

    /**
     *   关闭流
     * @param fos 文件输出流
     * @param is 输入流
     * @param zf 压缩文件
     * @param zos 压缩文件输出流
     * @return null
     */
    private void closeAll(FileOutputStream fos, InputStream is, ZipFile zf
            , ZipOutputStream zos, BufferedInputStream bis) {
        if(null != fos) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != bis) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != zos) {
            try {
                zos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != zf) {
            try {
                zf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

解压tar.gz的代码

package com.abc;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.compress.utils.IOUtils;

import java.io.*;

/**
 * @ClassName FileUtil
 * @Description {@link 'https://blog.csdn.net/u013066244/article/details/72783575'}
 * @Author hxm
 * @Date 2020-02-29 00:22
 **/
public class TarFileUtil {



        /**
         *   解压文件
         * @param TarFilePath 压缩文件的绝对路径,例如:C:/TarFileName.tar.gz
         * @param deCompressionPath 解压文件存放的路径,例如:C:/dir/
         */
        public void decomPression(String TarFilePath, String deCompressionPath) throws IOException {


                File sourceFile = new File(TarFilePath);
                TarArchiveInputStream fin = null;
                try {
                        fin = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(sourceFile)));
                        File extraceFolder = new File(deCompressionPath);
                        TarArchiveEntry entry;
                        // 将 tar 文件解压到 deCompressionPath 目录下
                        while ((entry = fin.getNextTarEntry()) != null) {
                                if (entry.isDirectory()) {
                                        continue;
                                }
                                File curfile = new File(extraceFolder, entry.getName());
                                File parent = curfile.getParentFile();
                                if (!parent.exists()) {
                                        parent.mkdirs();
                                }
                                // 将文件写出到解压的目录
                                IOUtils.copy(fin, new FileOutputStream(curfile));
                        }
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }finally {
                        closeAll(fin);
                }
        }

        public void  closeAll(TarArchiveInputStream fin){
                if(null != fin){
                        try{
                                fin.close();
                        }catch (IOException e){
                                e.printStackTrace();
                        }
                }
        }
}

创建Java Source

create or replace and compile java source named ziputils as
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @Description 解压缩文件工具类
 * @Author xuelin
 * @Date 2021/9/13
 * @Version 1.0.0
 */
public class ZipUtils {

    /**
     *   解压文件
     * @param zipFilePath 压缩文件的绝对路径,例如:C:/zipFileName.zip
     * @param deCompressionPath 解压文件存放的路径,例如:C:/dir/
     * @param readEncoding 解压时读出的文件编码格式,例如:GBK
     */
    public static void decompressionFile(String zipFilePath, String deCompressionPath, String readEncoding) {
        FileOutputStream fos = null;
        InputStream is = null;
        ZipFile zipFileItems = null;
        try {
            //  以指定格式打开zip文件
            zipFileItems = new ZipFile(zipFilePath , Charset.forName(readEncoding));
            //  获取zip文件的条目
            Enumeration<? extends ZipEntry> items = zipFileItems.entries();
            while(items.hasMoreElements()) {
                //  压缩文件中当前的所操作文件或文件夹的对象
                ZipEntry zipCurrentItem = items.nextElement();
                if(zipCurrentItem.isDirectory()) {//  遇到文件夹时深入文件夹递归
                    File newFile = new File(deCompressionPath+zipCurrentItem.getName());
                    if(!newFile.exists()) {
                        newFile.mkdirs();
                    }
                }else {
                    //  获取当前条目文件的输入流
                    is = zipFileItems.getInputStream(zipCurrentItem);
                    byte[] b = new byte[1024];
                    File newFile = new File(deCompressionPath+zipCurrentItem.getName());
                    if(!newFile.exists()) {
                        new File(deCompressionPath).mkdirs();// 创建路径
                        newFile.createNewFile();
                    }
                    fos = new FileOutputStream(newFile);
                    int len;
                    while((len = is.read(b)) != -1) {
                        fos.write(b, 0, len);
                    }
                }
            }
            zipFileItems.close();
        }catch (FileNotFoundException e) {
            e.fillInStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeAll(fos,is,zipFileItems,null,null);
        }
    }

    /**
     *   关闭流
     * @param fos 文件输出流
     * @param is 输入流
     * @param zf 压缩文件
     * @param zos 压缩文件输出流
     * @return null
     */
    private static void closeAll(FileOutputStream fos, InputStream is, ZipFile zf
            , ZipOutputStream zos, BufferedInputStream bis) {
        if(null != fos) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != bis) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != zos) {
            try {
                zos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(null != zf) {
            try {
                zf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

创建调用java source 的存储过程

create or replace procedure zipFilePsnInfo(srcPath  varchar,
                                           destPath varchar,
                                           zippwd   varchar) as
  language java name 'ZipUtils.decompressionFile(java.lang.String, java.lang.String,java.lang.String)';

创建遍历文件更新数据库信息的存储过程

create or replace procedure prc_psndoc_updateinfo is
       lineData varchar(500);-- 接收每行数据

       cur_file UTL_FILE.file_type;-- 获取文件访问游标

       sperloc1 smallint;-- 字符串分割符位置

       sperloc2 smallint;-- 字符串分割符位置

       sperloc3 smallint;-- 字符串分割符位置

       sperloc4 smallint;-- 字符串分割符位置

       sperloc5 smallint;-- 字符串分割符位置

       psncode varchar(10); --员工编号

       mobileno varchar(20);-- 手机号

       phoneno varchar(100);-- 电话号

       emailno varchar(100);-- 邮箱

       inSqlBase varchar(500) := 'update bd_psndoc set mobile=''@mobileno@'', homephone = ''@phoneno@'',email = ''@emailno@''  where code=''@psncode@'' ';-- 更新信息

       inSql varchar(500);-- 人员信息更新sql

       dealInfo varchar(4000) := '成功';-- 处理结果信息,默认为成功

       isSucess char(1) := 'Y';-- 处理标志,默认成功

       logSql varchar(500);-- 插入日志表sql

       begTime char(19) := to_char(sysdate, 'YYYY-MM-DD HH24:MI:SS');

       endTime char(19);

       fileName varchar(200);
begin
  
  -- 先解压文件
  zipFileWithPwd('F:\fileexpdir\oa_org_staff_20210914.zip', 'F:\test\', 'UTF-8');

  fileName := 'oa_org_staff_' || to_char(sysdate, 'YYYYMMDD') || '.dat';
  -- 打开文件
  cur_file := UTL_FILE.fopen('P_UPDATE', fileName, 'R', 32000);

  -- 循环文件游标处理每行数据
  loop
    UTL_FILE.get_line(cur_file, lineData);

    -- 获取分隔符位置
    sperloc1 := instr(lineData, '|+|', 1, 1);

    -- 获取分隔符位置
    sperloc2 := instr(lineData, '|+|', 1, 3);

    -- 获取分隔符位置
    sperloc3 := instr(lineData, '|+|', 1, 4);

    -- 获取分隔符位置
    sperloc4 := instr(lineData, '|+|', 1, 5);

    -- 获取分隔符位置
    sperloc5 := instr(lineData, '|+|', 1, 6);

    --截取员工号
    psncode := substr(lineData, 1, sperloc1 - 1);

    -- 截取手机号
    mobileno := substr(lineData, sperloc2 + 3, sperloc3 - (sperloc2 + 3));

    -- 截取电话号
    phoneno := substr(lineData, sperloc3 + 3,sperloc4 - (sperloc3 + 3));

    -- 截取邮箱
    emailno := substr(lineData, sperloc4 + 3,sperloc5 - (sperloc4 + 3));

    -- 转换插入语句
    inSql := replace(replace(replace(replace(inSqlBase, '@mobileno@', mobileno), '@phoneno@', phoneno),'@emailno@', emailno),'@psncode@',psncode);

    --执行更新人员信息sql
    --update bd_psndoc set mobile = mobileno, officephone = phoneno,email = emailno  where code=psncode;
    --commit;
    -- 执行
    execute immediate inSql;
    commit;
  end loop;

  -- 关闭文件
  UTL_FILE.fclose(cur_file);

  exception
    -- 捕获文件读取不到数据的异常
    when NO_DATA_FOUND then
      UTL_FILE.fclose(cur_file);
      endTime := to_char(sysdate, 'YYYY-MM-DD HH24:MI:SS');
      logSql := 'insert into hrs_ift_logs(pk_logs, workcode, workname, begtime, endtime, dealrst, dealinfo) values(''' || sys_guid() || ''', ''BD_PSNDOC'', ''更新人员信息'', ''' || begTime || ''',''' || endTime || ''', ''' || isSucess || ''', ''' || dealInfo || ''')';
      execute immediate logSql;
      -- 提交
      commit;
    -- 捕获其他异常,拿到错误信息
    when others then
      dealInfo := SQLCODE || ':' || SUBSTR(SQLERRM, 1, 200);
      isSucess := 'N';
      rollback;
      -- 将处理结果存储到日志表中
      logSql := 'insert into hrs_ift_logs(pk_logs, workcode, workname, begtime, endtime, dealrst, dealinfo) values(''' || sys_guid() || ''', ''BD_PSNDOC'', ''更新人员信息'', ''' || begTime || ''',''' || endTime || ''', ''' || isSucess || ''', ''' || dealInfo || ''')';
      execute immediate logSql;
      -- 提交
      commit;

end prc_psndoc_updateinfo;

存储过程中打开文件的参数设置

-- 打开文件
  cur_file := UTL_FILE.fopen('P_UPDATE', fileName, 'R', 32000);

-- UTL_FILE.fopen (location in varchar2, filename in varchar2, open_mode in varchar2) return FILE_TYPE;
Location 是路径参数,
FILENAME 是文件名,
OPEN_MODE是打开模式,'R'是读文本,'W'是写文本,'A'是附加文本,参数不分大小写,如果指定'A'但是文件不存在,它会用'W'先创建出来,'W'有覆盖的功能;

其中的location并不能简单的指定为'D:/temp'等路径,要建立一个DIRECTORY变量并付给权限(必须以DBA身份登录):

-- 创建 directory 的语句
create   or   replace  directory D_OUTPUT  as   'F:/test' ;  
grant   read ,write  on  directory D_OUTPUT  to  username;  
GRANT   EXECUTE   ON  utl_file  TO  username; 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值