java工作常用简单工具

3 篇文章 0 订阅

java工作常用简单工具

文件复制

当项目部署于服务器上时,文件的复制就没有那么方便了 
public class FileTransfer {
	public static void main(String[] args) throws IOException {
		String oldFilePath = "C:\\Users\\admin\\Desktop\\asd.txt";
		String newFilePath = "C:\\Users\\admin\\Desktop\\zzz.jpg";
		fileTransfer(oldFilePath, newFilePath);
	}
	public static void fileTransfer(String oldFilePath, String newFilePath) {
		try {
			File oldFile = new File(oldFilePath);
			if(!oldFile.exists()) {
        		return;
        	}
			File newFile = new File(newFilePath);
			File parentFile = newFile.getParentFile();
			if(!parentFile.exists()) {
				parentFile.mkdirs();
			}
			if(!newFile.exists()) {
				newFile.createNewFile();
			}
			InputStream in = new FileInputStream(oldFile);
        	OutputStream out = new FileOutputStream(newFile);
        	byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
            System.out.println(oldFilePath + "文件复制成功");
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println(oldFilePath + "文件复制失败");
			e.printStackTrace();
		}
	}
}

循环写入文件

有时需要将数据从数据库中读出,进行字符串拼接生成sql,写入指定文件
public class CycleWrite {
	public static void writeContent(BufferedWriter bw) {
		//TO DO
	}
	public static void main(String[] args) {
		String txtFilePath = "c:\\user\\admin\\desktop\\xxx.txt";
		cycleWrite(txtFilePath);
	}
	public static void cycleWrite(String txtFilePath) {
		BufferedWriter bw = null;
		FileWriter fileWriter = null;
		try {
			File file =new File(txtFilePath);
			if(!file.exists()){
	        	file.createNewFile();
	        }
			fileWriter = new FileWriter(file.getAbsoluteFile());
			bw = new BufferedWriter(fileWriter);
			//----------------------------------------------------------------
			writeContent(bw);
			//----------------------------------------------------------------
			//bw.write(xxxx);
			bw.close();
			fileWriter.close();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		System.out.println("写入完成");
	}
}

Txt文件读取

从txt文件中读取 拼接sql写入指定文件
public class ReadText {
	public static void main(String[] args) {
		String txtFilePath = "C:\\Users\\admin\\Desktop\\asd.txt";
		String targetFilePath = "C:\\Users\\admin\\Desktop\\xxx.txt";
		readTxt(txtFilePath, targetFilePath);
	}
	
	/**
	 * 	
	 * @param lineTxt 每一行的内容
	 * @param bw bw.write("xxx");
	 * @param index 索引
	 * @param tempMap 临时参数
	 * @throws IOException
	 */
	public static void operationTxtContent(BufferedWriter bw, String lineTxt, int index, Map tempMap) throws IOException {
		//TO DO
	}
	
	/**
	 * 	读取txt文件
	 * @param txtFilePath txt文件的路径
	 * @param targetFilePath 结果文件的路径
	 */
	public static void readTxt(String txtFilePath, String targetFilePath) {
		InputStream inputStream = null;
		InputStreamReader read = null;
		BufferedReader bufferedReader = null;
		BufferedWriter bw = null;
		FileWriter fileWriter = null;
		try {
			String encoding="UTF-8";
			File file = new File(txtFilePath);
			if(file.isFile() && file.exists()) {
				File outFile =new File(targetFilePath);
				if(!outFile.exists()){
					outFile.createNewFile();
		        }
				inputStream = new FileInputStream(file);
				read = new InputStreamReader(inputStream,encoding);//考虑到编码格式
				bufferedReader = new BufferedReader(read);
				
				fileWriter = new FileWriter(outFile.getAbsoluteFile());
				bw = new BufferedWriter(fileWriter);
				
				//每一行的字符串
                String lineTxt = null;
                //========================================================
                //临时参数封装
                Map tempMap = new HashMap();
                Connection content = SqlConnect.getSqlLiteContent();
                tempMap.put("connection", content);
                //========================================================
                int i = 0;
                while((lineTxt = bufferedReader.readLine()) != null){
                	//=================================================================
            		try {
            			operationTxtContent(bw, lineTxt, i, tempMap);
            			i++;
            		} catch(Exception e) {
            			e.printStackTrace();
            		}
                    //=================================================================
            		//bw.write(sql);
                }
			}else {
				System.out.println("文件不存在");
			}
			bw.close();
			fileWriter.close();
			bufferedReader.close();
			read.close();
			inputStream.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println("读取完成");
	}
}

xlsx表格读取

工作中难免需要操作xlsx 读出然后进行sql拼接 写入文件
需要POI的依赖
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.0.1</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.0.1</version>
</dependency>
public class ReadXlsx {
	public static void main(String[] args) {
		String xlsxFilePath = "C:\\Users\\admin\\Desktop\\xxx.xlsx";
		String targetFilePath = "C:\\Users\\admin\\Desktop\\test_appendfile_asd.txt";
		readXlsx(xlsxFilePath, targetFilePath);
	}
	/**
	 * 	操作内容
	 * @param bw 
	 * 	bw.write("xxx");
	 * @param row 当前行对象
	 * 	row.getCell(2).getStringCellValue();
	 * @param index 索引
	 */
	public static void operationXlsxContent(BufferedWriter bw, Row row, int index) {
		
	}
	public static void readXlsx(String xlsxFilePath, String targetFilePath) {
		BufferedWriter bw = null;
		FileWriter fileWriter = null;
		try {
			//用于解析 xls 文件
			//HSSFWorkbook wordbook = new HSSFWorkbook(new FileInputStream(new File(xlsxFilePath)));
			//用于解析 xls文件
			//HSSFSheet sheetAt = wordbook.getSheetAt(0);
			//用于解析 xlsx文件
			XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(xlsxFilePath)));
			//页签
			//用于解析 xlsx文件
			XSSFSheet sheetAt = workbook.getSheetAt(0);
			File file =new File(targetFilePath);
			if(!file.exists()){
	        	file.createNewFile();
	        }
			fileWriter = new FileWriter(file.getAbsoluteFile());
			bw = new BufferedWriter(fileWriter);
			
			//row.getCell(2).getStringCellValue();
			//======================================================
			int i = 0;
			for(Row row : sheetAt) {
				try {
					operationXlsxContent(bw, row, i);
					i++;
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
			//=======================================================
			//bw.write(sql);
			bw.close();
			fileWriter.close();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		System.out.println("读取完成");
	}
}

xlsx写入

当然这里的写入指的是循环写入 复杂性的写入 还是建议去直接手动去写
public class WriteXlsx {
	public static void main(String[] args) {
		String filePath = "C:\\Users\\admin\\Desktop\\test_appendfile_asd.xls";
		String sheetName = "月报表";
		
		List titleList = new ArrayList<String>();
		titleList.add("姓名");
		titleList.add("性别");
		
		List keyList = new ArrayList<String>();
		keyList.add("name");
		keyList.add("sex");
		
		List content = new ArrayList<Map>();
		Map map1 = new HashMap();
		map1.put("name", "张三");
		map1.put("sex", "女");
		content.add(map1);
		
		Map map2 = new HashMap();
		map2.put("name", "李四");
		map2.put("sex", "男");
		content.add(map2);
		writeXlsxList(filePath, sheetName, titleList, keyList, content);
	}
	
	public static void writeXlsxList(String filePath, String sheetName, List<String> titleList, List<String> keyList, List<Map> content) {
		writeXlsxMain(filePath, sheetName, "list", titleList, keyList, content);
	}
	
	private static void writeXlsxMain(String filePath, String sheetName, String type, List<String> titleList,List<String> keyList, List<Map> content) {
		FileOutputStream fOut = null;
		try {
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet(sheetName);
			//------------------------------------------------------------
			//写入列表
			xlsxContent(sheet, titleList, keyList, content);
			//-----------------------------------------------------------
			// 新建一输出文件流
			fOut = new FileOutputStream(filePath);
			// 把相应的Excel 工作簿存盘
			workbook.write(fOut);
			fOut.flush();
			// 操作结束,关闭文件
			fOut.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println("完毕");
	}
	/**
	 * 	写入列表
	 * @param sheet
	 */
	private static void xlsxContent(HSSFSheet sheet, List<String> titleList, List<String> keyList, List<Map> content) {
		
		if(titleList.size() != keyList.size()) {
			System.out.println("标题的长度与内容长度不一致");
			return;
		}
		
		int rowCount = 0;
		//第一行
		HSSFRow row = sheet.createRow(rowCount);
		rowCount++;
		//就有几列
		for(int i = 0;i < titleList.size();i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(titleList.get(i));
		}
		
		//就有几行
		for(Map contentMap : content) {
			row = sheet.createRow(rowCount);
			int i = 0;
			for(String key : keyList) {
				HSSFCell cell = row.createCell(i);
				cell.setCellValue(MapUtils.getString(contentMap, key));
				i++;
			}
			rowCount++;
		}
	}
}

数据库操作

提供一个简单的连接操作数据库的工具方法
public class MySqlCon {

	private static String driver = "com.mysql.cj.jdbc.Driver";
	
	private static String url = "jdbc:mysql://xxxxxx:3306/";
	private static String username = "xxxx";
	private static string password = "xxxx";
	
	public static Connection getConnect(String databaseName) {
		String url = url;
		url += databaseName;
		url += "?useSSL=false";
		return getConnect(driver, url, username, password);
	}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;

import cn.a2490.utils.PrintUtil;

public class ConnectUtil {

	/**
	 * 批量插入数量限制 每100000插入一次
	 */
	private static final int LIMIT_DATA = 100000;

	public static void startTransaction(Connection connection) throws SQLException {
		connection.setAutoCommit(false);
		System.out.println("-- START TRANSACTION -- ");
	}

	public static void rollback(Connection connection) throws SQLException {
		connection.rollback();
		connection.setAutoCommit(true);
		System.out.println("-- ROLLBACK TRANSACTION -- ");
	}

	public static void commit(Connection connection) throws SQLException {
		connection.commit();
		connection.setAutoCommit(true);
		System.out.println("-- COMMIT TRANSACTION -- ");
	}

	public static List<Map<String, Object>> executeQuery(String sql, Object[] param, Connection connection) {
		PreparedStatement prepareStatement = null;
		ResultSet resultSet = null;
		List<Map<String, Object>> resultList = null;
		try {
			prepareStatement = connection.prepareStatement(sql);
			if (param != null && param.length > 0) {
				for (int i = 0; i < param.length; i++) {
					prepareStatement.setObject((i + 1), param[i]);
				}
			}
			PrintUtil.print("sql => " + sql);
			PrintUtil.print("params => " + print(param));
			resultSet = prepareStatement.executeQuery();
			resultList = new ArrayList<Map<String, Object>>();
			while (resultSet.next()) {
				ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
				int count = resultSetMetaData.getColumnCount();
				Map<String, Object> result = new HashMap<String, Object>();
				for (int i = 0; i < count; i++) {
					String field = resultSetMetaData.getColumnName(i + 1);
					Object value = resultSet.getObject(field);
					if (value instanceof Clob) {
						result.put(field, clobToString((Clob) value));
					} else {
						result.put(field, value);
					}
				}
				resultList.add(result);
			}
			PrintUtil.print("result => " + print(resultList));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null) {
					resultSet.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (prepareStatement != null) {
					prepareStatement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return resultList;
	}

	public static String executeCount(String sql, Object[] param, Connection connection) {
		PreparedStatement prepareStatement = null;
		ResultSet resultSet = null;
		String result = null;
		try {
			prepareStatement = connection.prepareStatement(sql);
			if (param != null && param.length > 0) {
				for (int i = 0; i < param.length; i++) {
					prepareStatement.setObject((i + 1), param[i]);
				}
			}
			PrintUtil.print("sql => " + sql);
			PrintUtil.print("params => " + print(param));
			resultSet = prepareStatement.executeQuery();
			while (resultSet.next()) {
				result = resultSet.getString(1);
			}
			PrintUtil.print("result => [" + result + "]");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null) {
					resultSet.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (prepareStatement != null) {
					prepareStatement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 批量插入
	 * 
	 * @param sql
	 * @param paramList
	 * @param connection
	 * @return
	 */
	public static boolean insertBatch(String sql, List<Object[]> paramList, Connection connection) {
		boolean result = false;
		try (PreparedStatement prepareStatement = connection.prepareStatement(sql)) {
			if (paramList == null || paramList.size() <= 0) {
				throw new RuntimeException("请传入批量操作参数");
			}
			startTransaction(connection);
			if (paramList.size() <= LIMIT_DATA) {
				for (Object[] param : paramList) {
					for (int i = 0; i < param.length; i++) {
						prepareStatement.setObject((i + 1), param[i]);
					}
					prepareStatement.addBatch();
				}
			} else {
				for (int i = 1; i <= paramList.size(); i++) {
					Object[] param = paramList.get((i - 1));
					for (int j = 0; j < param.length; j++) {
						prepareStatement.setObject((j + 1), param[j]);
					}
					prepareStatement.addBatch();
					if (i % LIMIT_DATA == 0) {
						prepareStatement.executeBatch();
						prepareStatement.clearBatch();
					}
				}
			}
			if (paramList.size() % LIMIT_DATA != 0) {
				prepareStatement.executeBatch();
			}
			commit(connection);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			try {
				rollback(connection);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			result = false;
		}
		return result;
	}

	public static boolean execute(String sql, Object[] param, Connection connection) {
		PreparedStatement prepareStatement = null;
		boolean result = false;
		try {
			prepareStatement = connection.prepareStatement(sql);
			if (param != null && param.length > 0) {
				for (int i = 0; i < param.length; i++) {
					prepareStatement.setObject((i + 1), param[i]);
				}
			}
			PrintUtil.print("sql => " + sql);
			PrintUtil.print("params => " + print(param));
			result = prepareStatement.execute();
			PrintUtil.print("result => [" + result + "]");
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (prepareStatement != null) {
					prepareStatement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	private static String print(Object obj) {
		Gson gson = new Gson();
		return gson.toJson(obj);
	}

	private static String clobToString(Clob clob) throws SQLException, IOException {
		if (clob == null || clob.getCharacterStream() == null) {
			return "";
		}
		String reString = "";
		java.io.Reader is = clob.getCharacterStream();
		BufferedReader br = new BufferedReader(is);
		String s = br.readLine();
		StringBuffer sb = new StringBuffer();
		while (s != null) {
			sb.append(s);
			s = br.readLine();
		}
		reString = sb.toString();
		return reString;
	}

}

打印工具类

提供一个简易日志工具类

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;

import com.google.gson.Gson;

public class PrintUtil {

	public final static String INFO = "INFO";

	public final static String ERROR = "ERROR";

	/**
	 * 每行显示的长度
	 */
	private final static Integer PRINT_LENGTH = 120;

	/**
	 * 用于控制显示什么等级的信息 INFO ERROR
	 */
	private static String levelType = "INFO,ERROR";

	/**
	 * 是否根据等级进行显示
	 */
	private static boolean isFilterLevel = true;

	/**
	 * 用于控制打印的方式 out 控制台 file文件
	 */
	private static String printType = "out,file";

	private static String fileBasePath = "C:\\Users\\admin\\Desktop\\";

	private static int fileNameSuffix = 1;

	/**
	 * 用于控制日志文件的最大大小
	 */
	// 1M
	private static Long fileSize = 1048576L;

	private static File logFile = null;
	private static FileWriter fw = null;
	private static PrintWriter pw = null;

	static {
		try {
			if (printType != null && printType.contains("file") && fileBasePath != null) {
				openWriter();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void print(String prefix, String str) {
		try {
			if (str == null) {
				doPrint(prefix, "null");
				return;
			}
			if (PRINT_LENGTH != null) {
				if (str.length() <= PRINT_LENGTH) {
					doPrint(prefix, str);
					return;
				}
				int i = 1;
				int currIndex = 0;
				String tempStr = "";
				while (str.length() - currIndex >= 0) {
					int lastLength = i * PRINT_LENGTH;
					if (lastLength > str.length()) {
						lastLength = str.length();
					}
					tempStr = str.substring(currIndex, lastLength);
					currIndex = i * PRINT_LENGTH;
					i++;
					doPrint(prefix, tempStr);
				}
			} else {
				doPrint(prefix, str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void doPrint(String prefix, String oStr) throws IOException {
		String str = "";
		if (prefix != null && !"".equals(prefix)) {
			if (isFilterLevel) {
				if (levelType != null && !levelType.contains(prefix)) {
					return;
				}
			}
			str += "[" + prefix + "] " + oStr;
		} else {
			str = oStr;
		}
		if (pw != null) {
			pw.println(str);
			// 判断文件大小是否已经超预期
			// 至少1kb
			if (fileSize != null && fileSize > 1024) {
				if (logFile.length() > fileSize) {
					// 需要写入新的文件了
					closeWriter();
					openWriter();
				}
			}
		}
		if (printType != null && printType.contains("out")) {
			if (ERROR.equals(prefix)) {
				System.out.println("\033[31m" + str);
			} else {
				System.out.println(str);
			}
		}
	}

	public static void print(String prefix, Object object) {
		print(prefix, new Gson().toJson(object));
	}

	public static void info(Object object) {
		print(INFO, new Gson().toJson(object));
	}

	public static void error(Object object) {
		print(ERROR, new Gson().toJson(object));
	}

	public static void print(Object object) {
		print(new Gson().toJson(object));
	}

	public static void print(String str) {
		print(null, str);
	}

	public static String getLevelType() {
		return levelType;
	}

	public static void setLevelType(String levelType) {
		PrintUtil.levelType = levelType;
	}

	public static boolean isFilterLevel() {
		return isFilterLevel;
	}

	public static void setFilterLevel(boolean isFilterLevel) {
		PrintUtil.isFilterLevel = isFilterLevel;
	}

	private static void openWriter() throws IOException {
		LocalDate now = LocalDate.now();
		String fileName = now.toString();
		logFile = new File(fileBasePath + fileName + ".txt");
		while (logFile.exists()) {
			logFile = new File(fileBasePath + fileName + "_" + fileNameSuffix + ".txt");
			fileNameSuffix++;
		}
		fw = new FileWriter(logFile);
		pw = new PrintWriter(fw, true);
	}

	private static void closeWriter() throws IOException {
		if (pw != null) {
			pw.close();
		}
		if (fw != null) {
			fw.close();
		}
	}

	@Override
	protected void finalize() throws Throwable {
		closeWriter();
	}

	public static void main(String[] args) {
		print(INFO, "张三1");
		print(INFO, "张三2");
		print(ERROR, "张三3");
		print(ERROR, "张三4");
		print(ERROR, "张三5");
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值