Hutool工具包使用记录

1. SM2密钥对生成

1
2
3
4
5
6
7
SM2 sm2 = SmUtil.sm2();
byte[] b_privateKey = BCUtil.encodeECPrivateKey(sm2.getPrivateKey());
byte[] b_publicKey = ((BCECPublicKey) sm2.getPublicKey()).getQ().getEncoded(false);
String s_privateKey = HexUtil.encodeHexStr(b_privateKey).toUpperCase();
String s_publicKey= HexUtil.encodeHexStr(b_publicKey).toUpperCase();
System.out.println("!!!本地私钥: " + s_privateKey);
System.out.println("!!!本地公钥: " + s_publicKey);

2. http简单请求

1
2
3
4
5
6
 String url="htpp://127.0.0.1:8080/api";
Map<String, String> tmp =new HashMap();
String result2 = HttpRequest.post(url)
.body(JSONUtil.toJsonStr(tmp))
.execute().body();
log.info("收到 result:"+result2);

3. Convert类型转换

1
2
3
4
5
6
//string 转int
String x ="2";
int y = Convert.toInt(x,0);
//object > string
Object o="";
String x = Convert.toStr(o,"");

4. ftp上传文件

1
2
3
4
5
6
7
8
9
String filePath="d://123.jpg",tempPath ="/"+DateUtil.format(new Date(), "yyyyMMdd");
FtpConfig config = new FtpConfig();
config.setHost("127.0.0.1");
config.setPort(8080);
config.setUser("user");
config.setPassword("password");
Ftp ftp = new Ftp(config, FtpMode.Passive);
boolean b_result = ftp.upload(tempPath, FileUtil.file(filePath));
ftp.close();

5. 压缩多个文件夹中的所有文件到ZIP文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
    /**
* 压缩多个文件夹中的所有文件到ZIP文件
*
* @param sourceFolderPaths 要压缩的文件夹路径数组
* @param zipFilePath 输出的ZIP文件路径
* @param fileRenamer 一个函数,用于为每个文件指定新的名称(可以为null,表示不重命名)
* @throws IOException 如果发生I/O错误
*/
public static void compressFolders(Set<String> sourceFolderPaths, String zipFilePath,
java.util.function.Function<String, String> fileRenamer) throws IOException {
String parentPath = FileUtil.getParent(zipFilePath, 1);
File filePath = new File(parentPath);
if (!filePath.exists()) {
filePath.mkdirs();
}

try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
for (String sourceFolderPath : sourceFolderPaths) {
Path sourceFolder = Paths.get(sourceFolderPath);
if (!Files.isDirectory(sourceFolder)) {
continue;
}

// 为每个文件夹添加一个顶级目录(可选)
String folderBaseName = sourceFolder.getFileName().toString();

Files.walk(sourceFolder)
.filter(path -> !Files.isDirectory(path))
.forEach(path -> {
try {
// 计算相对路径
String relativePath = sourceFolder.relativize(path).toString();

// 应用重命名函数(如果提供)
String entryName = (fileRenamer != null) ? fileRenamer.apply(relativePath) : relativePath;

// 如果需要为每个文件夹添加顶级目录
if (sourceFolderPaths.size() > 1) {
entryName = folderBaseName + "/" + entryName;
}

// 确保路径使用正斜杠(ZIP规范)
entryName = entryName.replace(File.separatorChar, '/');

// 添加到ZIP文件
ZipEntry zipEntry = new ZipEntry(entryName);
zos.putNextEntry(zipEntry);

// 写入文件内容
Files.copy(path, zos);
zos.closeEntry();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
} catch (UncheckedIOException e) {
throw e.getCause();
}
}