jdbc和java文件处理


import java.io.*;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;


public class UserAsyMain implements Runnable {

    static Connection conn = null;
    static String path = "E:\\tmp";
//    static String path = "/home/srftp/usersyn";

    public static void main(String[] args) {
        UserAsyMain work = new UserAsyMain();
        work.run();
    }

    @Override
    public void run(){
        try {
            conn = getConn();
            // 关闭自动提交,即开启事务
            conn.setAutoCommit(false);

            while(true){
                deal(path);
                heartbeat();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                // 在把自动提交打开
                conn.setAutoCommit(true);
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    //文件入库
    public void deal(String path){
        List<File> files = getFileList(path);
        for(File f : files){
            System.out.println("2-"+f.getName());
            List<String[]> datas = readFileByLines(f.getAbsolutePath());
            updateUserInfo(datas);
            moveFile(path, f);
        }
    }

    public List<File> getFileList(String strPath) {
        List<File> filelist = new ArrayList<>();
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                if (files[i].isDirectory()) { // 判断是文件还是文件夹
                    continue;
                } else if (fileName.endsWith("temp")) { // 判断文件名是否以.avi结尾
                    continue;
                } else {
                    File file = files[i];
                    if(!file.renameTo(file)){
                        continue;
                    }
                    System.out.println(file.getName());
                    filelist.add(files[i]);
                }
            }
        }
        return filelist;
    }

    public void moveFile(String path, File file){
        Boolean flag = copyFile(file.getAbsolutePath(), path+"/his/"+file.getName());
        if(flag){
            deleteFile(file.getAbsolutePath());
        }
    }

    public static List<String[]> readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        List<String[]> list = new ArrayList<>();
        String[] dds = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                dds = tempString.split("\\|\\^\\|");
                list.add(dds);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return list;
    }

    public void updateUserInfo(List<String[]> list){
        System.out.println("updateUserInfo:"+list.size());
        String accNbr = "";
        for (String[] strs : list){
            accNbr = strs[0];
            if("3".equals(strs[5])){
                accNbr = strs[1]+accNbr;
            }
            //判断是否存在,存在则跳过
            if(selectUser(accNbr)){
                continue;
            }
            insertUserInfo(strs);
        }
    }
    static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static void insertUserInfo(String[] strs) {
        System.out.println("insertUserInfo: "+strs[0]+"-"+strs[1]);
        PreparedStatement pstm = null;
        try {
            String sql = "insert user_info(AREA_CODE,ACC_NBR,SYSTEM_ID,PROD_STATE,PROD_ID,PROD_TYPE_ID,PAY_TYPE," +
                    "STATE,STATE_DATE,CREATED_DATE,UPDATE_DATE,PARTY_TYPE,PARTY_CODE,USER_INFO_ID) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, strs[1].substring(1)); //AREA_CODE
            pstm.setString(2, "3".equals(strs[5]) ? strs[1]+strs[0] : strs[0]); //ACC_NBR
            pstm.setString(3, "2"); //SYSTEM_ID
            pstm.setString(4, "1"); //PROD_STATE
            pstm.setString(5, strs[3]); //PROD_ID
            pstm.setString(6, strs[5]); // PROD_TYPE_ID 用户类型
            pstm.setString(7, strs[2]); //PAY_TYPE
            pstm.setString(8, "A"); //STATE
            pstm.setString(9, dateFormat.format(new Date())); //STATE_DATE
            pstm.setString(10, dateFormat.format(new Date())); //CREATED_DATE
            pstm.setString(11, dateFormat.format(new Date())); //UPDATE_DATE
            pstm.setString(12, "E"); //PARTY_TYPE
            pstm.setString(13, "userasymain"); //PARTY_CODE
            pstm.setLong(14, nextSequence()); //PARTY_CODE
            pstm.execute();
            // 执行完后,手动提交事务
            conn.commit();
        } catch (SQLException e) {
            try {
                // 发生异常,事务回滚!
                if (conn != null && !conn.isClosed()) {
                    conn.rollback();
                    System.out.println("更新失败,事务回滚!");
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            if (pstm != null) {
                try {
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static Boolean selectUser(String accNbr) {
        System.out.print("selectUser: "+accNbr);
        Boolean ret = false;
        String sql = "select acc_nbr from user_info where acc_nbr = ? ";
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, accNbr);
            rs = pstm.executeQuery();
            while (rs.next()) {
                ret = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (pstm != null) {
                try {
                    rs.close();
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("-"+ret);
        return ret;
    }

    private static void heartbeat() {
        String sql = "select 1";
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();
            rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (pstm != null) {
                try {
                    rs.close();
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    protected static Long nextSequence() {
        Long ret = 0l;
        String sql = "SELECT USER_INFO_ID_SEQ.nextval as nextval";
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();
            while (rs.next()) {
                ret = rs.getLong(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (pstm != null) {
                try {
                    rs.close();
                    pstm.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }

    private static Connection getConn() {
//        String driver = "oracle.jdbc.driver.OracleDriver";
//        String url = " jdbc:oracle:thin:@127.0.0.1:1521:orcl";
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:8901/testdb?autoReconnect=true";
        String username = "test";
        String password = "Test@2019";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }



        /**
         * 复制单个文件
         * @param oldPath 原文件路径
         * @param newPath 复制后路径
         */
        public static Boolean copyFile(String oldPath, String newPath) {
            InputStream inStream = null; //读入原文件
            FileOutputStream fs = null;
            try {
                int bytesum = 0;
                int byteread = 0;
                File oldfile = new File(oldPath);
                if (oldfile.exists()) { //文件存在时
                    inStream = new FileInputStream(oldPath); //读入原文件
                    fs = new FileOutputStream(newPath);
                    byte[] buffer = new byte[1444];
                    int length;
                    while ( (byteread = inStream.read(buffer)) != -1) {
                        bytesum += byteread; //字节数 文件大小
                        fs.write(buffer, 0, byteread);
                    }
                    return true;
                }
            }
            catch (Exception e) {
                System.out.println("复制单个文件操作出错");
                e.printStackTrace();
            }finally {
                try {
                    if(inStream != null){
                        inStream.close();
                    }
                    if(fs != null){
                        fs.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            return false;
        }

        /**
         * 复制整个文件夹内容
         * @param oldPath String 原文件路径 如:c:/fqf
         * @param newPath String 复制后路径 如:f:/fqf/ff
         * @return boolean
         */
        public static void copyFolder(String oldPath, String newPath) {

            try {
                (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
                File a=new File(oldPath);
                String[] file=a.list();
                File temp=null;
                for (int i = 0; i < file.length; i++) {
                    if(oldPath.endsWith(File.separator)){
                        temp=new File(oldPath+file[i]);
                    }
                    else{
                        temp=new File(oldPath+File.separator+file[i]);
                    }

                    if(temp.isFile()){
                        FileInputStream input = new FileInputStream(temp);
                        FileOutputStream output = new FileOutputStream(newPath + "/" +
                                (temp.getName()).toString());
                        byte[] b = new byte[1024 * 5];
                        int len;
                        while ( (len = input.read(b)) != -1) {
                            output.write(b, 0, len);
                        }
                        output.flush();
                        output.close();
                        input.close();
                    }
                    if(temp.isDirectory()){//如果是子文件夹
                        copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                    }
                }
            }
            catch (Exception e) {
                System.out.println("复制整个文件夹内容操作出错");
                e.printStackTrace();

            }

        }

        /**
         * 删除文件
         * @param fileName
         * @return
         */
        public static boolean deleteFile(String fileName) {
            File file = new File(fileName);
            // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    return true;
                } else {
                    return false;
                }
            } else {
                System.out.println("删除单个文件失败:" + fileName + "不存在!");
                return false;
            }
        }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

军大_j

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值