常用Java代码
标题色值(#3366ff)
1、文件读取
try { String path = "待读取文件的地址"; BufferedReader inputStream = new BufferedReader(new FileReader(path)); String line = inputStream.readLine(); while(line != null) { System.out.println(line); line = inputStream.readLine(); } if(inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); }
2、文件写入(覆盖写入)
try { String path = "待写入文件的地址"; BufferedWriter outputStream = new BufferedWriter(new FileWriter(path)); for(int i=0; i<10; i++) { String line = "123"; outputStream.write(line+"\n"); } if(outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); }
3、字符数组类型转 String
char chs[] = new char[100]; ....read(chs); String str = String.valueOf(chs).trim();
4、休眠
try { Thread.sleep(1200); } catch (InterruptedException e) { e.printStackTrace(); }
5、正则表达式匹配
String str = "123"; Pattern p = Pattern.compile("^\\d+$"); Matcher m = p.matcher(str); if(!m.find()) { // 操作 }
6、随机整数
// [3,19) int num = (int)(Math.random()*16+3);
7、MD5 加密
import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
byte[] digest = null; String str = "Hello"; try { MessageDigest md5 = MessageDigest.getInstance("md5"); digest = md5.digest(str.getBytes("utf-8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //16是表示转换为16进制数 String md5Str = new BigInteger(1, digest).toString(16); System.out.println(md5Str);
8、AES 加密解密
import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class Main { public static void main(String[] args) throws Exception { String content = "待加密明文"; String password = "加密密码"; byte[] encrypt = MyAESUtil.encrypt(content, password); // 加密 String hexStr = MyAESUtil.parseByte2HexStr(encrypt); // 将加密后的二进制密文转为十六进制密文 System.out.println(hexStr); byte[] binStr = MyAESUtil.parseHexStr2Byte(hexStr); // 将十六进制密文转为二进制,进行解密 byte[] decrypt = MyAESUtil.decrypt(binStr, password); // 解密 System.out.println(new String(decrypt, "utf-8")); } } class MyAESUtil { // 加密 public static byte[] encrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] result = cipher.doFinal(byteContent); return result; } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } // 解密 public static byte[] decrypt(byte[] content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] result = cipher.doFinal(content); return result; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } // 将二进制转换成16进制 public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } // 将16进制转换为二进制 public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length()/2]; for (int i = 0;i< hexStr.length()/2; i++) { int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16); int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16); result[i] = (byte) (high * 16 + low); } return result; } }AES 加密解密
9、排序
import java.util.Arrays; import java.util.Comparator; public class Main { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { Student[] stu = new Student[6]; stu[0] = new Student(19205101, "XiaoMing", 65); stu[1] = new Student(19205102, "LiFei", 85); stu[2] = new Student(19205103, "HuangYi", 77); stu[3] = new Student(19205104, "ZhangJin", 53); stu[4] = new Student(19205105, "HeYing", 85); stu[5] = new Student(19205106, "ZhaoLi", 90); Comparator cmp = new MyComparator(); Arrays.sort(stu, cmp); for(int i=0; i排序) { System.out.println(stu[i].toString()); } } } class MyComparator implements Comparator { @Override public int compare(Student s1, Student s2) { // 如果是int,double这种基本类型,要用它们对应的类Integer,Double return s2.getGrade() - s1.getGrade(); } } class Student { private int id; private String name; private int grade; public Student(int id, String name, int grade) { this.id = id; this.name = name; this.grade = grade; } public String toString() { return id + "," + name + "," + grade; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } }
10、获取时间
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); System.out.println(dtf.format(now)); // 推荐下面这种 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); System.out.println(sdf.format(date));
11、两个时刻间隔
Calendar calendar = Calendar.getInstance(); calendar.set(2001, 5, 2, 15, 30, 0); // 设置时间 Date date1 = calendar.getTime(); // 2001-05-02 15:30:00 Date date2 = new Date(); // 现在的时刻 long d1 = date1.getTime(); long d2 = date2.getTime(); int seconds = (int)((d2-d1)/1000); // 相差的秒数 System.out.println(seconds/60/60/24/365);
12、遍历文件夹
import java.io.File; public class Main { public static void main(String[] args) { String path = "要遍历的根目录"; func1(path); File file = new File(path); func2(file); } // 遍历文件夹下所有文件 public static void func1(String path) { File file = new File(path); File[] fs = file.listFiles(); for(int i=0; i遍历文件夹) { if(!fs[i].isDirectory()) { System.out.println(fs[i]); } } } // 遍历文件夹下所有文件以及文件夹内的文件 public static void func2(File file) { File[] fs = file.listFiles(); for(int i=0; i ) { if(fs[i].isFile()) { System.out.println(fs[i]); } if(fs[i].isDirectory()) { func2(fs[i]); } } } }
13、文件操作(基于Java 8)
创建一个类FileUtil,将代码内容全部复制进去即可。
原文:Java压缩、复制文件及解压zip
import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * 文件工具 * * @author JZY */ public class FileUtil { /** * 默认缓冲数组大小 */ private static final int DEFAULT_BUFFER_SIZE = 8192; /** * 保持结构 */ private static final boolean KEEP_STRUCTURE = true; /** * 保留空文件夹 */ private static final boolean KEEP_EMPTY_FOLDER = true; /** * 默认编码格式 */ private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; /** * 兼容性编码格式 */ private static final Charset COMPATIBLE_ENCODING = Charset.forName("GBK"); /** * 获取不带后缀的文件名 * * @param fileName 文件名 * @return 不带后缀的文件名 */ public static String getFileNameWithoutSuffix(String fileName) { int endIndex = fileName.lastIndexOf("."); if (endIndex != -1) { return fileName.substring(0, endIndex); } else { return fileName; } } /** * 获取不带后缀的文件名 * * @param file 文件 * @return 不带后缀的文件名 */ public static String getFileNameWithoutSuffix(File file) { return getFileNameWithoutSuffix(file.getName()); } /** * 获取文件后缀 * * @param fileName 文件名 * @return 文件后缀 */ public static String getFileSuffix(String fileName) { int endIndex = fileName.lastIndexOf("."); if (endIndex != -1) { return fileName.substring(endIndex + 1); } else { return null; } } /** * 获取文件后缀 * * @param file 文件 * @return 文件后缀 */ public static String getFileSuffix(File file) { return getFileSuffix(file.getName()); } /** * 创建所有必须但不存在的父文件夹 * * @param parentFolderPath 父文件夹路径 * @throws IOException IO异常 */ public static void createParentFolder(String parentFolderPath) throws IOException { createParentFolder(new File(parentFolderPath)); } /** * 创建所有必须但不存在的父文件夹 * * @param parentFolder 父文件夹 * @throws IOException IO异常:创建父文件夹(父目录)失败 */ public static void createParentFolder(File parentFolder) throws IOException { if (!parentFolder.exists()) { if (!parentFolder.mkdirs()) { throw new IOException("创建父文件夹(父目录)“" + parentFolder.getPath() + "”失败"); } } } /** * 文件转字节数组 * * @param file 文件 * @return 字节数组 * @throws IOException IO异常 */ public static byte[] fileToByte(File file) throws IOException { return fileToByte(file, new byte[DEFAULT_BUFFER_SIZE]); } /** * 文件转字节数组 * * @param file 文件 * @param bufferSize 缓冲区大小 * @return 字节数组 * @throws IOException IO异常 */ public static byte[] fileToByte(File file, int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } return fileToByte(file, new byte[bufferSize]); } /** * 文件转字节数组 * * @param file 文件 * @param buffer 缓冲区 * @return 字节数组 * @throws IOException IO异常 */ public static byte[] fileToByte(File file, byte[] buffer) throws IOException { try ( FileInputStream fileInputStream = new FileInputStream(file); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ) { int length; while ((length = fileInputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, length); } byteArrayOutputStream.flush(); return byteArrayOutputStream.toByteArray(); } } /** * 复制文件 * * @param sourceFile 源文件 * @param targetFile 目标文件 * @throws IOException IO异常 */ public static void copyFile(File sourceFile, File targetFile) throws IOException { copyFile(sourceFile, targetFile, new byte[DEFAULT_BUFFER_SIZE]); } /** * 复制文件 * * @param sourceFile 源文件 * @param targetFile 目标文件 * @param bufferSize 缓冲区大小 * @throws IOException IO异常 */ public static void copyFile(File sourceFile, File targetFile, int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } copyFile(sourceFile, targetFile, new byte[bufferSize]); } /** * 复制文件 * * @param sourceFile 源文件 * @param targetFile 目标文件 * @param buffer 缓冲区 * @throws IOException IO异常 */ public static void copyFile(File sourceFile, File targetFile, byte[] buffer) throws IOException { try ( FileInputStream fileInputStream = new FileInputStream(sourceFile); FileOutputStream fileOutputStream = new FileOutputStream(targetFile) ) { int length; while ((length = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, length); } fileOutputStream.flush(); } } /** * 复制文件夹 * * @param sourceFolder 源文件夹 * @param targetFolder 目标文件夹 * @throws IOException IO异常 */ public static void copyFolder(File sourceFolder, File targetFolder) throws IOException { copyFolder(sourceFolder, targetFolder, new byte[DEFAULT_BUFFER_SIZE]); } /** * 复制文件夹 * * @param sourceFolder 源文件夹 * @param targetFolder 目标文件夹 * @param bufferSize 缓冲区大小 * @throws IOException IO异常 */ public static void copyFolder(File sourceFolder, File targetFolder, int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } copyFolder(sourceFolder, targetFolder, new byte[bufferSize]); } /** * 复制文件夹 * * @param sourceFolder 源文件夹 * @param targetFolder 目标文件夹 * @param buffer 缓冲区 * @throws IOException IO异常 */ public static void copyFolder(File sourceFolder, File targetFolder, byte[] buffer) throws IOException { copyFolderContent(sourceFolder, new File(targetFolder.getPath(), sourceFolder.getName()), buffer); } /** * 复制文件夹内容 * * @param sourceFolder 源文件夹 * @param targetFolder 目标文件夹 * @throws IOException IO异常 */ public static void copyFolderContent(File sourceFolder, File targetFolder) throws IOException { copyFolderContent(sourceFolder, targetFolder, new byte[DEFAULT_BUFFER_SIZE]); } /** * 复制文件夹内容 * * @param sourceFolder 源文件夹 * @param targetFolder 目标文件夹 * @param bufferSize 缓冲区大小 * @throws IOException IO异常 */ public static void copyFolderContent(File sourceFolder, File targetFolder, int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } copyFolderContent(sourceFolder, targetFolder, new byte[bufferSize]); } /** * 复制文件夹内容 * * @param sourceFolder 源文件夹 * @param targetFolder 目标文件夹 * @param buffer 缓冲区 * @throws IOException IO异常 */ public static void copyFolderContent(File sourceFolder, File targetFolder, byte[] buffer) throws IOException { if (sourceFolder.isDirectory()) { createParentFolder(targetFolder); File[] files = sourceFolder.listFiles(); if (files != null && files.length > 0) { String sourceFolderPath = sourceFolder.getPath(); String targetFolderPath = targetFolder.getPath(); String fileName; for (File file : files) { fileName = file.getName(); copyFolderContent(new File(sourceFolderPath, fileName), new File(targetFolderPath, fileName), buffer); } } } else { copyFile(sourceFolder, targetFolder, buffer); } } /** * 压缩文件 * * @param sourceFile 源文件 * @param targetFile 目标文件 * @throws IOException IO异常 */ public static void compressFile(File sourceFile, File targetFile) throws IOException { compressFile(sourceFile, targetFile, new byte[DEFAULT_BUFFER_SIZE]); } /** * 压缩文件 * * @param sourceFile 源文件 * @param targetFile 目标文件 * @param bufferSize 缓冲区大小 * @throws IOException IO异常 */ public static void compressFile(File sourceFile, File targetFile, int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } compressFile(sourceFile, targetFile, new byte[bufferSize]); } /** * 压缩文件 * * @param sourceFile 源文件 * @param targetFile 目标文件 * @param buffer 缓冲区 * @throws IOException IO异常 */ public static void compressFile(File sourceFile, File targetFile, byte[] buffer) throws IOException { try ( FileOutputStream fileOutputStream = new FileOutputStream(targetFile); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream, DEFAULT_ENCODING) ) { compressFile(sourceFile, sourceFile.getName(), buffer, zipOutputStream); } } /** * 压缩文件 * * @param sourceFile 源文件 * @param fileName 文件名 * @param zipOutputStream Zip输出流 * @throws IOException IO异常 */ public static void compressFile(File sourceFile, String fileName, ZipOutputStream zipOutputStream) throws IOException { compressFile(sourceFile, fileName, new byte[DEFAULT_BUFFER_SIZE], zipOutputStream); } /** * 压缩文件 * * @param sourceFile 源文件 * @param fileName 文件名 * @param buffer 缓冲区 * @param zipOutputStream Zip输出流 * @throws IOException IO异常 */ public static void compressFile(File sourceFile, String fileName, byte[] buffer, ZipOutputStream zipOutputStream) throws IOException { try ( FileInputStream fileInputStream = new FileInputStream(sourceFile) ) { zipOutputStream.putNextEntry(new ZipEntry(fileName)); int length; while ((length = fileInputStream.read(buffer)) != -1) { zipOutputStream.write(buffer, 0, length); } zipOutputStream.flush(); } } /** * 压缩文件夹 * * @param sourceFolder 源文件夹 * @param targetFile 目标文件 * @throws IOException IO异常 */ public static void compressFolder(File sourceFolder, File targetFile) throws IOException { compressFolder(sourceFolder, targetFile, new byte[DEFAULT_BUFFER_SIZE], KEEP_STRUCTURE, KEEP_EMPTY_FOLDER); } /** * 压缩文件夹 * * @param sourceFolder 源文件夹 * @param targetFile 目标文件夹 * @param bufferSize 缓冲区大小 * @param keepStructure 保持结构(如不保持结构,则所有文件、文件夹均在压缩包的根目录下) * @param keepEmptyFolder 保留空文件夹 * @throws IOException IO异常 */ public static void compressFolder(File sourceFolder, File targetFile, int bufferSize, boolean keepStructure, boolean keepEmptyFolder) throws IOException { compressFolder(sourceFolder, targetFile, new byte[bufferSize], keepStructure, keepEmptyFolder); } /** * 压缩文件夹 * * @param sourceFolder 源文件 * @param targetFile 目标文件 * @param buffer 缓冲区 * @param keepStructure 保持结构(如不保持结构,则所有文件、文件夹均在压缩包的根目录下) * @param keepEmptyFolder 保留空文件夹 * @throws IOException IO异常 */ public static void compressFolder(File sourceFolder, File targetFile, byte[] buffer, boolean keepStructure, boolean keepEmptyFolder) throws IOException { try ( FileOutputStream fileOutputStream = new FileOutputStream(targetFile) ) { ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); compressFolder(sourceFolder, "", buffer, zipOutputStream, keepStructure, keepEmptyFolder); } } /** * 压缩文件夹 * * @param sourceFolder 源文件 * @param fileName 文件名 * @param zipOutputStream Zip输出流 * @throws IOException IO异常 */ public static void compressFolder(File sourceFolder, String fileName, ZipOutputStream zipOutputStream) throws IOException { compressFolder(sourceFolder, fileName, new byte[DEFAULT_BUFFER_SIZE], zipOutputStream, KEEP_STRUCTURE, KEEP_EMPTY_FOLDER); } /** * 压缩文件夹 * * @param sourceFolder 源文件 * @param fileName 文件名 * @param buffer 缓冲区 * @param zipOutputStream Zip输出流 * @throws IOException IO异常 */ public static void compressFolder(File sourceFolder, String fileName, byte[] buffer, ZipOutputStream zipOutputStream) throws IOException { compressFolder(sourceFolder, fileName, buffer, zipOutputStream, KEEP_STRUCTURE, KEEP_EMPTY_FOLDER); } /** * 压缩文件夹 * * @param sourceFolder 源文件 * @param fileName 文件名 * @param buffer 缓冲区 * @param zipOutputStream Zip输出流 * @param keepStructure 保持结构(如不保持结构,则所有文件、文件夹均在压缩包的根目录下) * @param keepEmptyFolder 保留空文件夹 * @throws IOException IO异常 */ public static void compressFolder(File sourceFolder, String fileName, byte[] buffer, ZipOutputStream zipOutputStream, boolean keepStructure, boolean keepEmptyFolder) throws IOException { if (sourceFolder.isDirectory()) { if (keepEmptyFolder) { zipOutputStream.putNextEntry(new ZipEntry(fileName + "/")); } File[] files = sourceFolder.listFiles(); if (files != null && files.length > 0) { String currentFileName; String newFileName; for (File file : files) { currentFileName = file.getName(); newFileName = fileName; if (keepStructure) { newFileName = newFileName + File.separator + currentFileName; } compressFolder(new File(sourceFolder.getPath(), currentFileName), newFileName, buffer, zipOutputStream, keepStructure, keepEmptyFolder); } } } else { compressFile(sourceFolder, fileName, buffer, zipOutputStream); } } /** * 解压 * * @param sourceCompressFile 源压缩文件 * @param targetFolder 目标文件夹 * @throws IOException IO异常 */ public static void decompress(File sourceCompressFile, File targetFolder) throws IOException { decompress(sourceCompressFile, targetFolder, new byte[DEFAULT_BUFFER_SIZE]); } /** * 解压缩 * * @param sourceCompressFile 源压缩文件 * @param targetFolder 目标文件夹 * @param bufferSize 缓冲区大小 * @throws IOException IO异常 */ public static void decompress(File sourceCompressFile, File targetFolder, int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } decompress(sourceCompressFile, targetFolder, new byte[bufferSize]); } /** * 解压缩 * * @param sourceCompressFile 源压缩文件 * @param targetFolder 目标文件夹 * @param buffer 缓冲区 * @throws IOException IO异常 */ public static void decompress(File sourceCompressFile, File targetFolder, byte[] buffer) throws IOException { try ( FileInputStream fileInputStream = new FileInputStream(sourceCompressFile); ZipInputStream zipInputStream = new ZipInputStream(fileInputStream, COMPATIBLE_ENCODING) ) { createParentFolder(targetFolder); ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { if (zipEntry.getName().endsWith("/") || zipEntry.getName().endsWith("\\")){ File newFolder = new File(targetFolder.getPath(), zipEntry.getName()); createParentFolder(newFolder); }else { decompress(new File(targetFolder.getPath(), zipEntry.getName()), buffer, zipInputStream); } zipEntry = zipInputStream.getNextEntry(); } } } /** * 解压缩 * * @param targetFile 目标文件 * @param buffer 缓冲区 * @param zipInputStream Zip输入流 * @throws IOException IO异常 */ public static void decompress(File targetFile, byte[] buffer, ZipInputStream zipInputStream) throws IOException { try ( FileOutputStream fileOutputStream = new FileOutputStream(targetFile) ) { int length; while ((length = zipInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, length); } fileOutputStream.flush(); } } }文件操作