Java常用工具方法使用心得

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/diyangxia/article/details/78873501

每批一万处理大数据集合

这种分批处理主要用于mysql数据处理上

         List<String> list = new ArrayList<>();
        for(int i = 0 ;i< 51254;i ++){
            list.add("pp"+i);
        }
        int size = list.size();
        for (int i = 0; i < size; i+=Config.EVERY_NUM) {
            int suffix = Config.EVERY_NUM;
            if(i+Config.EVERY_NUM > size){
                suffix = size - i;
            }
            List<String> sublist = list.subList(i,i+suffix);
            System.out.println(sublist.size());
        }

输出

10000
10000
10000
10000
10000
1254

判断字符串是否为数字

public static boolean isInteger(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
  }

或者使用StringUtils自带的函数

public static boolean isNumeric(String str){
    for (int i = str.length();--i>=0;){  
        if (!Character.isDigit(str.charAt(i))){
            return false;
        }
    }
    return true;
 }

获取url的ip

  try {
            String bankurl = "https://directbank.czbank.com/APPINSPECT/finance/creditCardApyOnlineCardSel.jsp";
            URL url = new URL(bankurl);
            InetAddress[] ips = InetAddress.getAllByName(url.getHost());
            for (InetAddress ip : ips) {
                System.out.println(ip.toString());
                System.out.println("Address:" + ip.getHostAddress());
                System.out.println("Name:" + ip.getHostName());
            }
        }catch (Exception e){
            e.printStackTrace();
        }

这里获取到到ip应该是真实到ip,不经过dns,绕过cdn

解压、压缩文件夹

java自带的压缩api只能操作普通的文件,要想操作加密的zip文件,就得用到

         <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>1.3.2</version>
        </dependency>

具体代码如下:
zip4j–处理带密码的zip包

 public static void unzip(File zipFile, String dest, String passwd) throws ZipException {
        ZipFile zFile = new ZipFile(zipFile);  // 首先创建ZipFile指向磁盘上的.zip文件
        zFile.setFileNameCharset("GBK");       // 设置文件名编码,在GBK系统中需要设置
        if (!zFile.isValidZipFile()) {   // 验证.zip文件是否合法,包括文件是否存在、是否为zip文件、是否被损坏等
            throw new ZipException("压缩文件不合法,可能被损坏.");
        }
        File destDir = new File(dest);     // 解压目录
        if (destDir.isDirectory() && !destDir.exists()) {
            destDir.mkdir();
        }
        if (zFile.isEncrypted()) {
            zFile.setPassword(passwd.toCharArray());  // 设置密码
        }
        zFile.extractAll(dest);      // 将文件抽出到解压目录(解压)
    }

解压zip文件不带密码的到指定文件夹
Java实现zip文件解压[到指定目录]

 /**
     * 解压到指定目录
     *
     * @param zipPath
     * @param descDir
     */
    public static void unZipFiles2(String zipPath, String descDir) throws IOException {
        unZipFilesNew(new File(zipPath), descDir);
        delFolder(descDir + "/__MACOSX");
    }

    /**
     * 解压文件到指定目录
     * 解压后的文件名,和之前一致
     *
     * @param zipFile 待解压的zip文件
     * @param descDir 指定目录
     */
    @SuppressWarnings("rawtypes")
    public static void unZipFilesNew(File zipFile, String descDir) throws IOException {

        ZipFile zip = new ZipFile(zipFile, Charset.forName("UTF-8"));//解决中文文件夹乱码
        String name = zip.getName().substring(zip.getName().lastIndexOf('\\') + 1, zip.getName().lastIndexOf('.'));

        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }

        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + "/" + zipEntryName).replaceAll("\\*", "/");

            // 判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            // 输出文件路径信息
//          System.out.println(outPath);

            FileOutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        System.out.println("******************解压完毕********************");
        return;
    }

压缩文件不带密码的

 /**
     * 压缩文件夹
     *
     * @param dirPath
     * @param zipName http://www.jb51.net/article/115212.htm
     */
    public static void zipFiles(String dirPath, String zipName) {
        List<String> srcfile = getFiles(dirPath);
        byte[] buf = new byte[1024];
        try {
            //ZipOutputStream类:完成文件或文件夹的压缩
            File zipFile = new File(zipName);
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
            for (int i = 0; i < srcfile.size(); i++) {
                File file = new File(srcfile.get(i));
                FileInputStream in = new FileInputStream(file);
                out.putNextEntry(new ZipEntry(file.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
            System.out.println("压缩完成.");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

执行命令行命令

Runtime.getRuntime().exec()执行重定向命令方法

  private void moveFile(String srcFilePath, String destFilePath) {
        try {
            Runtime runtime = Runtime.getRuntime();
            String[] cmd = {"sh", "-c", "mv " + srcFilePath + " " + destFilePath};
            Process outputCsvDecrypt = runtime.exec(cmd);
            int outputExitVal = outputCsvDecrypt.waitFor();
            System.out.println("移动结果" + outputExitVal);
            if (outputExitVal == 0) {
                System.out.println(srcFilePath + "移动成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

SimpleDateFormat月日不显示0

https://blog.csdn.net/KingWTD/article/details/48089111

      SimpleDateFormat format = new SimpleDateFormat("yyyyMd");
        System.out.println(format.format(new Date()));
        2018511

List汉字排序

https://blog.csdn.net/jky_yihuangxing/article/details/50736154

  List<String> list=new ArrayList<>();
        list.add("河南");
        list.add("江苏");
        list.add("福建");
        list.add("甘肃");
        list.add("北京");
 Collections.sort(list, Collator.getInstance(java.util.Locale.CHINA));

删除空文件夹

 /**
     * 删除空文件夹
     * @param folderPath
     */
    public static void delFolder(String folderPath) {
        try {
            //实例化File
            File myFilePath = new File(folderPath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

获取文件夹下所有文件名

Java-读取某个目录下所有文件、文件夹和3种从文件路径中获取文件名的方法

public static ArrayList<String> getFiles(String path) {
        ArrayList<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
            }
        }
        return files;
    }

从字符串中提取数字

java从字符串中提取数字

                String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(str);
                String id = m.replaceAll("").trim();
                System.out.println("--------------id" + id);

以上输入为

group.data163.data

或者

group.data163

输出为

163

替换最后一个,仿replaceFirst方法

https://stackoverflow.com/questions/2282728/java-replacelast

public static String replaceLast(String text, String regex, String replacement) {
        return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement);
    }
    public static void main(String[] args) {
        System.out.println(replaceLast("foo AB bar AB AB car AB done", "AB", "--"));
    }

以上输出内容为

foo AB bar AB AB car -- done

取两位小数

        int a = 2;
        double b = 10000;
        DecimalFormat decimalFormat=new DecimalFormat("######0.00");
        System.out.println(decimalFormat.format(a/b*100)+"%");
        输出:0.02%

判断日期是否在某一段日期内

        String dateStr= "02/11/2017 18:36:57";
        String startDate = "2017-02-11";
        String endDate = "2017-02-13";
                System.out.println(Utils.getFormatDate(dateStr,startDate,endDate));
输出:在
public static boolean getFormatDate(String dateStr, String inputDate) {
        boolean isIncurrentDay = false;
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        try {
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
            String fileDate = format2.format(format.parse(dateStr));
            if (fileDate.equals(inputDate)) {
                System.out.println("在");
                isIncurrentDay = true;
            } else {
                System.out.println("不在");
                isIncurrentDay = false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return isIncurrentDay;
    }

    public static boolean getFormatDate(String dateStr, String startDate, String endDate) {
        boolean isInDuration = false;
        try {
            SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
            Date dateS = format2.parse(format2.format(format.parse(dateStr)));
            Date startS = format2.parse(startDate);
            Date endS = format2.parse(endDate);
            if (!dateS.after(endS) && !dateS.before(startS)) {
                System.out.println("在");
                isInDuration = true;
            } else {
                System.out.println("不在");
                isInDuration = false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return isInDuration;
    }

获取项目配置文件中的变量值

第一种

Properties property = new Properties();
        try {
            property.load(new FileInputStream("你的文件位置"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String value = property.getProperty("你的属性的key");

第二种,推荐使用

 java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("email");
        String keystore = bundle.getString("mysql.decrystore"); //获取值

txt文件最后一行文件内容覆写并追加

  public static void rewriteendline(String filepath, String string)
            throws Exception {

        RandomAccessFile file = new RandomAccessFile(filepath, "rw");
        long len = file.length();
        long start = file.getFilePointer();
        long nextend = start + len - 1;

        int i = -1;
        file.seek(nextend);
        byte[] buf = new byte[1];

        while (nextend > start) {

            i = file.read(buf, 0, 1);
            if (buf[0] == '\r') {
                file.setLength(nextend - start);
                break;
            }
            nextend--;
            file.seek(nextend);

        }
        file.close();
        writeendline(filepath, string);

    }

    public static void writeendline(String filepath, String string)
            throws Exception {

        RandomAccessFile file = new RandomAccessFile(filepath, "rw");
        long len = file.length();
        long start = file.getFilePointer();
        long nextend = start + len - 1;
        byte[] buf = new byte[1];
        file.seek(nextend);
        file.read(buf, 0, 1);

        if (buf[0] == '\n')

            file.writeBytes(string);
        else

            file.writeBytes("\r\n" + string);

        file.close();

    }

字符串中获取手机号

 /**
     * 只取字符串中11位的数字是否为手机号,如果有多个,逗号隔开
     * @param text
     * @return
     */
    public static String getPhone11(String text){
        Pattern pattern = Pattern.compile("(?<!\\d)(?:(?:1[358]\\d{9})|(?:861[358]\\d{9}))(?!\\d)");
        Matcher matcher = pattern.matcher(text);
        StringBuffer bf = new StringBuffer(64);
        while (matcher.find()) {
            bf.append(matcher.group()).append(",");
        }
        int len = bf.length();
        if (len > 0) {
            bf.deleteCharAt(len - 1);
        }
        return bf.toString();
    }
    /**
     * 查询符合的手机号码,包括从12位数字中截取手机号
     * @param str
     */
    public static void checkCellphone(String str){
        // 将给定的正则表达式编译到模式中
        Pattern pattern = Pattern.compile("((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}");
        // 创建匹配给定输入与此模式的匹配器。
        Matcher matcher = pattern.matcher(str);
        //查找字符串中是否有符合的子字符串
        while(matcher.find()){
            //查找到符合的即输出
            System.out.println("查询到一个符合的手机号码:"+matcher.group());
        }
    }

/**同上
**/
    private static String checkNum(String num){
        if(num == null || num.length() == 0){return "";}
        Pattern pattern = Pattern.compile("(?<!\\d)(?:(?:1[358]\\d{9})|(?:861[358]\\d{9}))(?!\\d)");
        Matcher matcher = pattern.matcher(num);
        StringBuffer bf = new StringBuffer(64);
        while (matcher.find()) {
            bf.append(matcher.group()).append(",");
        }
        int len = bf.length();
        if (len > 0) {
            bf.deleteCharAt(len - 1);
        }
        return bf.toString();
    }

    private static boolean isNumLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
阅读更多

没有更多推荐了,返回首页