使用工具类

文章目录

  • 使用工具类
    • 1.上传文件
    • 2.输入工具
    • 3.链接数据库
    • 4.Service响应
    • 5.阿里数据库连接池Druid.
    • 6.ajax数据返回格式

最近头一次写项目用到了几个工具类写下来以后继续改进现阶段只满足基本的使用功能不是很完善

1.上传文件

public class FileUtil {private FileUtil() {}private static final String TARGET_DIRECTORY = "upload/user";public static String fileUpload(String sourceFilePath) {String data = LocalDate.now().toString();String pictureName = sourceFilePath.substring(sourceFilePath.lastIndexOf(File.separatorChar) + 1);File childDirectory = new File(TARGET_DIRECTORY, data);if (!childDirectory.exists()) {childDirectory.mkdirs();}String uuidStr = UUID.randomUUID().toString().replaceAll("-", "");String fileName = uuidStr +"-"+pictureName;File targetFilePath = new File(childDirectory, fileName);String path = "";try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFilePath));BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(targetFilePath));) {byte[] bytes = new byte[1024];int len = 0;while ((len = bufferedInputStream.read(bytes)) != -1) {bufferedOutputStream.write(bytes, 0, len);}path = targetFilePath.getPath();System.out.println("文件上传成功 " + path);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return path;}
}

2.输入工具

public class InputUtil {private InputUtil() {}private static Scanner input;static {input = new Scanner(System.in);}//提供2个静态的方法public static int inputInt() {return input.nextInt();}public static float inputFloat(){ return input.nextFloat();}public static double inputDouble(){ return input.nextDouble();}public static BigDecimal inputBigDecimal (){ return input.nextBigDecimal();}public static int inputInt(String regex, String msg) {while (true) {String str = input.next();if (str.matches(regex)) {return Integer.parseInt(str);}System.out.println(msg);}}public static String inputStr() {input.nextLine();return input.nextLine();}public static String inputNextStr() {return input.next();}}

3.链接数据库

3.1 jdbc.properties

username=root
password=root
url=jdbc:mysql://192.168.12.250:3306/sms?useSSL=true&characterEncoding=utf8
driver=com.mysql.jdbc.Driver

3.2 PrpUtil

public class PropUtil {PropUtil() {}private static Properties properties;static {properties = new Properties();try {properties.load(PropUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));Class.forName(PropUtil.getValue("driver"));} catch (IOException | ClassNotFoundException e) {e.printStackTrace();}}public static String getValue(String key) {return properties.getProperty(key," ");}
}

3.3 DBHelper

public class DBHelper {private DBHelper() {}private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal() {@Override@SneakyThrowsprotected Object initialValue() {return DriverManager.getConnection(PropUtil.getValue("url"), PropUtil.getValue("password"), PropUtil.getValue("username"));}};public static Connection getCon() {return THREAD_LOCAL.get();}public static void closeResources(Connection connection,PreparedStatement ps,ResultSet rs) {Objects.requireNonNull(connection);Objects.requireNonNull(ps);Objects.requireNonNull(rs);try {rs.close();ps.close();connection.close();THREAD_LOCAL.remove();} catch (SQLException e) {e.printStackTrace();}}public static void closeResources(Connection connection,PreparedStatement ps) {Objects.requireNonNull(connection);Objects.requireNonNull(ps);try {ps.close();connection.close();THREAD_LOCAL.remove();} catch (SQLException e) {e.printStackTrace();}}public static void closeResources(Connection connection) {Objects.requireNonNull(connection);try {connection.close();THREAD_LOCAL.remove();} catch (SQLException e) {e.printStackTrace();}}
}

4.Service响应

4.1 CodeEnum

public enum  CodeEnum {SUCCESS("success",200),ERROR("error",403);private String msg;private Integer code;public String getMsg(){ return msg;}public Integer getCode(){return code;}CodeEnum(String msg,Integer code){this.msg = msg;this.code = code;}
}

4.2 ServerResponseResult

@Data
public class ServerResponseResult<D> {private String message;private Integer status;private D data;public static <D> ServerResponseResult<D> success(D data) {return new ServerResponseResult<>(CodeEnum.SUCCESS.getMsg(), CodeEnum.SUCCESS.getCode(), data);}public static <D> ServerResponseResult<D> success(String msg, D data) {return new ServerResponseResult<>(msg, CodeEnum.SUCCESS.getCode(), data);}public static <D> ServerResponseResult<D> success() {return new ServerResponseResult<>(CodeEnum.SUCCESS.getMsg(), CodeEnum.SUCCESS.getCode());}public static <D> ServerResponseResult<D> error(){return new ServerResponseResult<>(CodeEnum.ERROR.getMsg(),CodeEnum.ERROR.getCode());}public ServerResponseResult(String message, Integer status, D data) {this.message = message;this.status = status;this.data = data;}public ServerResponseResult(String message, Integer status) {this.message = message;this.status = status;}public ServerResponseResult() {}}

5.阿里数据库连接池Druid.

阿里数据库连接池Druid.
配置文件

username=root
password=root
url=jdbc:mysql://192.168.12.250:3306/test?useSSL=true&characterEncoding=utf8
driverClassName=com.mysql.jdbc.Driver
initalSize=8
maxActive=801

主代码


import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;public class DBHelpers {private DBHelpers() {}private static DataSource dataSource;static {Properties properties = new Properties();try {properties.load(DBHelpers.class.getClassLoader().getResourceAsStream("jdbc.properties"));dataSource = DruidDataSourceFactory.createDataSource(properties);} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}public static Connection getCon(){try {return dataSource.getConnection();} catch (SQLException e) {e.printStackTrace();}return null;}public static DataSource getDataSource(){return dataSource;}}

6.ajax数据返回格式

public enum  ReturnCode {UNAME_OK(20000,"用户名可用"),UNAME_WRONG(20001,"用户名重复"),REQ_SUCCESS(10000,"操作成功"),NO_DATA(10001,"没有数据");private Integer rcode;private String rmsg;ReturnCode(Integer rcode, String rmsg) {this.rcode = rcode;this.rmsg = rmsg;}public Integer getRcode() {return rcode;}public String getRmsg() {return rmsg;}
}

返回数据实体

public class ReturnEntity {private Integer code;private String msg;private Object data;public ReturnEntity() {}public ReturnEntity(Integer code, String msg, Object data) {this.code = code;this.msg = msg;this.data = data;}
}

常用工具类(初级中的初级)相关推荐

  1. commons-lang3-3.2.jar中的常用工具类的使用

    这个包中的很多工具类可以简化我们的操作,在这里简单的研究其中的几个工具类的使用. 1.StringUtils工具类 可以判断是否是空串,是否为null,默认值设置等操作: /*** StringUti ...

  2. commons-lang常用工具类StringEscapeUtils使用--转

    https://my.oschina.net/ydsakyclguozi/blog/341496 在apache commons-lang(2.3以上版本)中为我们提供了一个方便做转义的工具类,主要是 ...

  3. java arrays方法_Java工具类Arrays中不得不知的常用方法

    原标题:Java工具类Arrays中不得不知的常用方法 Arrays 数组操作集数组转List ---asList 这个被"普遍"称为数组转List的方法,可能是Arrays内大家 ...

  4. java file ip_java常用工具类 IP、File文件工具类

    本文实例为大家分享了java常用工具类的具体实现代码,供大家参考,具体内容如下 IP工具类 package com.jarvis.base.util; import java.io.IOExcepti ...

  5. javascript 总结(常用工具类的封装)(转)

    转载地址:http://dzblog.cn/article/5a6f48afad4db304be1e7a5f javascript 总结(常用工具类的封装) JavaScript 1. type 类型 ...

  6. apache-commons 常用工具类

    引用包说明 本文引用的所有包如下 <dependency><groupId>org.apache.commons</groupId><artifactId&g ...

  7. javascript 总结(常用工具类的封装,转)

    javascript 总结(常用工具类的封装) 前言 因为工作中经常用到这些方法,所有便把这些方法进行了总结. JavaScript 1. type 类型判断 isString (o) { //是否字 ...

  8. 6章:常用工具类以及函数

    2019独角兽企业重金招聘Python工程师标准>>> <div class="box"><div class="w_320" ...

  9. javascript常用工具类整理(copy)

    JavaScript常用工具类 类型 日期 数组 字符串 数字 网络请求 节点 存储 其他 1.类型 isString (o) { //是否字符串return Object.prototype.toS ...

  10. commons-lang常用工具类StringEscapeUtils使用

    2019独角兽企业重金招聘Python工程师标准>>> 在apache commons-lang(2.3以上版本)中为我们提供了一个方便做转义的工具类,主要是为了防止sql注入,xs ...

最新文章

  1. python生成器单线程_【Python】迭代器、生成器、yield单线程异步并发实现详解
  2. 明明还有空间,硬盘却写不进去了!
  3. 诚通网盘会员很坑的,升级会员的人要注意
  4. ES5 和ES6 继承机制
  5. 容器编排技术 -- 使用Minikube集群
  6. 使用JAVA加jxl jar操作EXECL
  7. SAP License:SAP系统与ERP系统的区别是什么?
  8. Windows Workflow Foundation(一)(转载)
  9. Vue.js 2.6尝鲜
  10. 微信公众号完美解决关注后三次获取media_id重复3次的问题
  11. c#实现16进制和字符串之间转换
  12. Python3中.whl文件介绍
  13. linux的tar命令详情;linux多个文件压缩打包到一个压缩文件
  14. C#学习纪要(8):7月17日
  15. iOS应用开发入门(1)——第一个iOS应用
  16. C语言005:常见例题
  17. 接口测试介绍以及实践超详细篇
  18. Mac之时间机器的使用
  19. 非法字符: '\ufeff' 解决方案(Android Studio)
  20. 第六篇 | C语言中将键盘输入的两个整数进行交换

热门文章

  1. python实现判断一个字符串是否是合法IP地址
  2. 大数据基础(一)——关系+文章
  3. 操作系统 关于死锁的面试题
  4. 编译链接错误:对‘vtable for xxxx’未定义的引用
  5. Python下opencv(图像的阈值处理)
  6. 配置mysql字符_mysql字符设置
  7. 构造方法之间如何调用?
  8. setInterval()与setTimeout()
  9. redis技术分享ppt_技术分享丨华为鲲鹏架构Redis知识二三事
  10. 以太坊虚拟机 EVM(2)Solidity运行原理