首页 > 编程语言 >java 常用的包

java 常用的包

时间:2023-12-19 11:24:20浏览次数:36  
标签:常用 java String System cell null StringUtils out

org.apache.commons.lang.StringUtils 常用方法

    <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-lang3</artifactId>
       <version>3.4</version>
  </dependency>

示例:

import org.apache.commons.lang.StringUtils;
 
public class Test{
    @SuppressWarnings({ "deprecation", "unused" })
    public static void test(String[] args) {
    	
    	/*************************判   空**********************************/
    	//判断是否Null 或者 "" 【不去空格】为空的标准是 str==null 或 str.length()==0 
    	boolean isEmpty = StringUtils.isEmpty("");//true
    	boolean isEmpty1 = StringUtils.isEmpty("  ");//false
    	boolean isEmptyNull = StringUtils.isEmpty(null);//true
    	// 判断是否Null 或者 "" 【去空格】为空的标准是 str==null 或 str.length()==0 
    	boolean isBlack = StringUtils.isBlank("");//true
    	boolean isBlack1 = StringUtils.isBlank("  ");//true
    	boolean isBlankNull = StringUtils.isBlank(null);//true
    	
    	
        //找到2个字符串第一个出现不同的位置(1开始)
        String difference = StringUtils.difference("s123", "s13");
        System.out.println(difference);//3
        
        //判断2个字符串是否相等
        boolean equals = StringUtils.equals("s1", "s1");
        System.out.println(equals);//true
        
        // 不区分大小写判断两个字符串是都相等
        boolean equalsIgnoreCase = StringUtils.equalsIgnoreCase("abc", "ABc");//true
        System.out.println(equalsIgnoreCase);
        
        //判断字符串里面是否含有特定字符串
        boolean b2 = StringUtils.contains("asd", "as");
        System.out.println(b2);//true
 
        //把数组的元素用:进行拼接
        String concatStr = StringUtils.join(new String[]{"dog", "cat", "monkey"},":");
        System.out.println(concatStr);//dog:cat:monkey
 
        //根据特定分隔符对字符串进行拆分
        String[] split = StringUtils.split("apple|xiaomi|dell|lenovo", "|");
        for (String s1 : split) {
            System.out.print(s1 + "、");//apple、xiaomi、dell、lenovo、
        }
        System.out.println();
        
        //所有单词首字母大写
        String capitaliseAllWords = StringUtils.capitaliseAllWords("today i will go to china");
        System.out.println(capitaliseAllWords);//Today I Will Go To China
 
        //统计某个字符串在字符串出现的次数
        int matchCount = StringUtils.countMatches("Happy Birthday to you", "o");
        System.out.println(matchCount);//2
 
        //必须要8位,不够的就拿0去字符串左边补 
        String leftPad = StringUtils.leftPad("54", 8, "0");
        System.out.println(leftPad);//00000054
        
        //必须要8位,不够的就拿0去字符串右边补 
        String rightPad = StringUtils.rightPad("54", 8, "0");
        System.out.println(rightPad);//54000000
 
        //判断字符串是否以特定字符串开头,区分大小写
        boolean startsWith = StringUtils.startsWith("GoodMorning", "go");
        System.out.println(startsWith);//false
        
        //判断字符串是否以特定字符串结尾,区分大小写
        boolean endsWith = StringUtils.endsWith("GoodMorning", "ing");
        System.out.println(endsWith);//true
        
        // 去空格
        StringUtils.trim("      222     ");//222
        
        //将null和""转换为null
        StringUtils.trimToNull("");//null
        
        // 将null和""转换为""
        StringUtils.trimToEmpty(null);//""
 
        //当第一个字符串为null或者""时返回第二个参数
        StringUtils.defaultIfEmpty(null, "sos");//sos
        StringUtils.defaultIfEmpty("", "sos");//sos
        StringUtils.defaultIfEmpty("111", "sos");//111
        
        // 去除参数首尾和第二个参数相同的字符,如果第二个参数为null那就去除首尾的空格
        StringUtils.strip("fsfsdf", "f");//sfsd
        StringUtils.strip("fsfsdfa", "f");//sfsdfa
        // 去除首部和第二个参数相同的字符,如果第二个参数为null那就去除首部的空格
        StringUtils.stripStart("ddsuuud", "d");//suuud
        // 去除尾部和第二个参数相同的字符,如果第二个参数为null那就去除尾部的空格
        StringUtils.stripEnd("ddsuuud", "d");//ddsuuu
        
        // 对数组整体去除首尾空格
        //java
        //c++
        //python    script
        String[] strip = StringUtils.stripAll(new String[]{"    java ", "c++     ", "python    script"});
    	for(String aa : strip){
    		System.out.println(aa);
    	}
        
    	// 去掉数据中首尾和第二个参数一样的字符
    	//java
        //hp
        //ython    script
        String[] strip1 = StringUtils.stripAll(new String[]{"    java ", "php     ", "python    script"},"p");
    	for(String aa : strip){
    		System.out.println(aa);
    	}
        
    	/**************************查找****************************/
    	// 查找第二个参数首次出现的位置(区分大小写),如果第一个参数为null或者没有查找到时返回-1
    	StringUtils.indexOf("bbbb", "a");//-1
    	StringUtils.indexOf(null, "a");//-1
    	StringUtils.indexOf("aaaa", "a");//0
    	StringUtils.indexOf("aaaa", "A");//-1
    	
    	// 查找第二个参数首次出现的位置(不区分大小写),如果第一个参数为null或者没有查找到时返回-1
    	StringUtils.indexOf("bbbb", "A");//-1
    	StringUtils.indexOf(null, "A");//-1
    	StringUtils.indexOf("aaaa", "A");//0
    	
    	
    }
    
    public static void main(String[] args) {
    	System.out.println(StringUtils.indexOfIgnoreCase("abbb", "A"));
	}
    
}

@Data(Lombok实现)

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.22</version>
			<optional>true</optional>
		</dependency>

示例

package com.example.lombok;

import lombok.Data;

@Data
public class Student {
	private Integer id;
	private String name;
	private Integer gender;
	private Integer classId;
}

可选配置 如果想要在 Maven 打包的时候,Lombok 不被打包,可使用如下配置。

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

java利用POI解析Excel及图片

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
package com.betawoo.admin.test.base;
import com.betawoo.admin.commons.utils.QiNiuUtils;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by hgg on 2019/5/7.
 */
public class POIExcel {
    public static void getDataFromExcel(String filePath) throws IOException
    {
        //判断是否为excel类型文件
        if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx"))
        {
            System.out.println("文件不是excel类型");
        }
        FileInputStream fis =null;
        Workbook wookbook = null;
        Sheet sheet =null;
        try
        {
            //获取一个绝对地址的流
            fis = new FileInputStream(filePath);
            /* 读取网络文件(比如七牛等云存储)
            URL url = new URL(filePath);
            BufferedInputStream fis = new BufferedInputStream(url.openStream());*/
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        try
        {
            //2003版本的excel,用.xls结尾
            wookbook = new HSSFWorkbook(fis);//得到工作簿
        }
        catch (Exception ex)
        {
            //ex.printStackTrace();
            try
            {
                //2007版本的excel,用.xlsx结尾
                fis = new FileInputStream(filePath);
                wookbook = new XSSFWorkbook(fis);//得到工作簿
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        Map<String, PictureData> maplist=null;
        sheet = wookbook.getSheetAt(0);
        // 判断用07还是03的方法获取图片
        if (filePath.endsWith(".xls")) {
            maplist = getPictures1((HSSFSheet) sheet);
        } else if(filePath.endsWith(".xlsx")){
            maplist = getPictures2((XSSFSheet) sheet);
        }
        try {
            printImg(maplist);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放map
            if (maplist != null){
                maplist = null;
            }
        }
        //得到一个工作表
        //获得表头
        Row rowHead = sheet.getRow(0);
		
        //获得数据的总行数
        int totalRowNum = sheet.getLastRowNum();
        //要获得属性
        String proName="";
        String space="";
        String size="";
        String brand="";
        String unit="";
        Integer num=null;
        Double unitPrice=null;
        Double total=null;
        String material="";
        String remark="";
        String pic="";
        //获得所有数据
        System.out.println("产品名称\t\t空间\t\t规格/尺寸\t\t品牌\t\t单位\t\t数量\t\t单价\t\t金额\t\t材质\t\t备注");
        for(int i = 1 ; i < totalRowNum ; i++)
        {
            //获得第i行对象
            Row row = sheet.getRow(i);
            
            //空间位置(为空则停止解析)
            Cell cell = row.getCell(0);
            if (cell == null){
                break;
            }
            cell.setCellType(CellType.STRING);
            space =cell.getStringCellValue().toString();
            if (StringUtils.isBlank(space)){
                break;
            }
 
            //产品名称
            cell = row.getCell(1);
            if (cell != null){
                cell.setCellType(CellType.STRING);
                proName =  cell.getStringCellValue();
            }
            //规格/尺寸
            cell = row.getCell(3);
            if (cell != null){
                cell.setCellType(CellType.STRING);
                size =cell.getStringCellValue()+"";
            }
            //品牌
            cell = row.getCell(4);
            if (cell != null){
                cell.setCellType(CellType.STRING);
                brand =cell.getStringCellValue()+"";
            }
            //单位
            cell = row.getCell(5);
            if (cell != null){
                cell.setCellType(CellType.STRING);
                unit =cell.getStringCellValue()+"";
            }
            //数量
            cell = row.getCell(6);
            if (cell != null){
                num =(int)cell.getNumericCellValue();
            }
            //单价
            cell = row.getCell(7);
            if (cell != null){
                unitPrice =cell.getNumericCellValue();
            }
            //金额
            cell = row.getCell(8);
            if (cell != null){
                total =cell.getNumericCellValue();
            }
            //材质
            cell = row.getCell(9);
            if (cell != null){
                cell.setCellType(CellType.STRING);
                material =cell.getStringCellValue()+"";
            }
            //备注
            cell = row.getCell(10);
            if (cell != null){
                cell.setCellType(CellType.STRING);
                remark =cell.getStringCellValue()+"";
            }
            System.out.println(proName+"\t\t"+space+"\t\t"+size+"\t\t"+brand+"\t\t"+unit+"\t\t"+num+"\t\t"
                    +unitPrice+"\t\t"+total+"\t\t"+material+"\t\t"+remark);
        }
        for (Map.Entry<String, PictureData> entry : maplist.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        //使用完成关闭
        wookbook.close();
        if (fis != null){
            fis.close();
        }
    }
    /**
     * 获取图片和位置 (xls)
     * @param sheet
     * @return
     * @throws IOException
     */
    public static Map<String, PictureData> getPictures1 (HSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
        for (HSSFShape shape : list) {
            if (shape instanceof HSSFPicture) {
                HSSFPicture picture = (HSSFPicture) shape;
                HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
                PictureData pdata = picture.getPictureData();
                String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
                map.put(key, pdata);
            }
        }
        return map;
    }
    /**
     * 获取图片和位置 (xlsx)
     * @param sheet
     * @return
     * @throws IOException
     */
    public static Map<String, PictureData> getPictures2 (XSSFSheet sheet) throws IOException {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        List<POIXMLDocumentPart> list = sheet.getRelations();
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = picture.getPreferredSize();
                    CTMarker marker = anchor.getFrom();
                    String key = marker.getRow() + "-" + marker.getCol();
                    map.put(key, picture.getPictureData());
                }
            }
        }
        return map;
    }
    //图片写出
    public static void printImg(Map<String, PictureData> sheetList) throws Exception {
        Object key[] = sheetList.keySet().toArray();
        String filePath = "";
        for (int i = 0; i < sheetList.size(); i++) {
            // 获取图片流
            PictureData pic = sheetList.get(key[i]);
            // 获取图片索引
            String picName = key[i].toString();
            // 获取图片格式
            String ext = pic.suggestFileExtension();
            byte[] data = pic.getData();
            //文件上传七牛
//            QiNiuUtils.uploadOneObject(data,"111_"+picName + "." + ext);
            //图片保存路径
            filePath = "D:\\img\\pic" + picName + "." + ext;
            System.out.println(filePath);
            FileOutputStream out = new FileOutputStream(filePath);
            out.write(data);
            out.close();
        }
    }
    public static void main(String[] args) throws Exception {
        getDataFromExcel("D:"+ File.separator +"test.xlsx");
    }
}

标签:常用,java,String,System,cell,null,StringUtils,out
From: https://www.cnblogs.com/hefeng2014/p/17913261.html

相关文章

  • Matlab常用小技巧及部分快捷键
    Matlab常用小技巧一:1.m文件如果是函数,保存的文件名最好与函数名一致,这点都很清楚。不过容易疏忽的是,m文件名的命名尽量不要是简单的英文单词,最好是由大小写英文/数字/下划线等组成。原因是简单的单词命名容易与matlab内部函数名同名,结果会出现一些莫名其妙的错误。例如,写个m文件......
  • Unity3D 程序员常用的核心类及方法详解
    Unity3D是一款强大的游戏引擎,广泛应用于游戏开发领域。作为Unity3D程序员,掌握常用的核心类及方法是非常重要的。本文将详细介绍Unity3D中程序员常用的核心类及方法,并给出代码实现。对啦!这里有个游戏开发交流小组里面聚集了一帮热爱学习游戏的零基础小白,也有一些正在从事游戏开发......
  • Linux安装nacos 启动报错解决: which: no javac in (/usr/local/sbin:/usr/local/bin:
    报错信息:which:nojavacin(/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)readlink:缺少操作数Try'readlink--help'formoreinformation.dirname:缺少操作数Try'dirname--help'formoreinformation.ERROR:PleasesettheJAVA_HOME......
  • Java-并发编程-03深入理解并发编程概念以及相关关键字
    浅入并发编程三个核心概念在并发编程中,我们通常会遇到以下三个问题:原子性问题,可见性问题,有序性问题。我们先看具体看一下这三个概念:1.原子性原子性:即一个操作或者多个操作要么全部执行并且执行的过程不会被任何因素打断,要么就都不执行。举个最简单的例子,大家想一下假如为一......
  • 游刃有余:玩转Java泛型
    Java中的泛型提供了一种创建可以处理不同类型数据的可重用代码的方法。它允许用户定义可操作各种数据类型的类、接口和方法,而无需牺牲类型安全性。在Java5中引入的泛型已经成为Java编程语言的一个基本特性。在Java引入泛型之前,它使用原始类型来允许将各种类型的对象存储在......
  • linux的一些不常用指令
    一:文件操作//-----------------------阅读文件----------------------------//1、vi/vim文件名   --------------不存在的文件新建,存在的编辑2、cat-n文件名  -----------------显示文件的行号3、vim+行号文件名 -------------编辑并跳到指定行4、more文件......
  • Java面向对象程序设计(上海交通大学出版社)12章及以后的课后问题解析
    1)Map集合和Collection集合的区别是什么? Map集合和Collection集合都是Java集合框架中的接口,它们之间有一些关键的区别:元素存储方式:Collection:用于存储单一元素的集合接口。它继承自Iterable接口,包含常见的子接口如List、Set。Map:用于存储键值对(key-value......
  • JavaScript 中 let、var 和 const 的区别及使用建议
    前言JavaScript中的let、var和const是三种不同的变量声明方式。虽然它们都可以用来声明变量,但它们之间有很大的区别。在本篇文章中,我们将深入探讨这三种变量声明方式的区别以及它们在实际开发中的应用。正文内容一、let的用法let是ES6中新增的变量声明方式,它的作用域......
  • 无涯教程-Java - SortedSet 集合接口函数
    SortedSet接口扩展了Set并声明了按升序排序的集合的行为。除了Set定义的那些方法外,SortedSet接口还声明了下表中概述的方法-如果尝试使用null对象并且集合中不允许使用null,则抛出NullPointerException。Sr.No.Method&Remark1Comparatorcomparator()返回调用排序集的比......
  • java基础语法之二维数组1
    一:概述在前面的博文中,已经说明了一维数组相关的基础知识和案例,接下来就是对二维数组的介绍。首先介绍二维数组的相关基础介绍。二:具体说明二维数组:元素为一维数组的数组。<1>二维数组的定义格式数据类型[][]变量名; int[][]arr; 数据类型变量名[][]; intarr[][];数据类型[]......