操作jar包内文件以及jar包内jar包里文件的方法

#操作jar包内文件以及jar包内jar包里文件的方法

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
package com.supcon.supfusion.framework.cloud.i18n.resource.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JarUtil {


// public static void main(String args[]) {
//
// JarUtil f = new JarUtil();
// f.instal();
// }

/**
* 安装jar包
*/
private void instal() {
System.out.println("Start Installing Portal......");
System.out.println("Start Extracting File......");

String jarFileName = "portal.jar";
Date d = new Date();
String outputPath = "portal" + d;
try {
//执行解压
decompress(jarFileName, outputPath);
System.out.println("Extracting OK!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Extracting File Failed!");
dealError(outputPath);
System.out.println("Installing Portal Failed");
return;
}

String systemName = System.getProperty("os.name");
System.out.println("System is " + systemName);
//如果是unix系列操作系统则赋予用户可执行权限
if (!systemName.toLowerCase().contains("windows")) {
System.out.println("Start Granting User Excecute Rights......");
try {
Process p1 = Runtime.getRuntime().exec("chmod +x portal.sh");
p1.waitFor();
Process p2 = Runtime.getRuntime().exec("portal.sh");
p2.waitFor();
System.out.println("Granting User Excecute Rights OK!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Granting User Excecute Rights Failed!");
dealError(outputPath);
System.out.println("Installing Portal Failed");
return;
}
}
}


/**
* 解压缩JAR包
*
* @param fileName 文件名
* @param outputPath 解压输出路径
* @throws IOException IO异常
*/
private void decompress(String fileName, String outputPath) throws IOException {

if (!outputPath.endsWith(File.separator)) {
outputPath += File.separator;

}
JarFile jf = new JarFile(fileName);
for (Enumeration e = jf.entries(); e.hasMoreElements(); ) {
JarEntry je = (JarEntry) e.nextElement();
String outFileName = outputPath + je.getName();
File f = new File(outFileName);
System.out.println(f.getAbsolutePath());

//创建该路径的目录和所有父目录
makeSupDir(outFileName);

//如果是目录,则直接进入下一个循环
if (f.isDirectory()) {
continue;
}

InputStream in = null;
OutputStream out = null;

try {
in = jf.getInputStream(je);
out = new BufferedOutputStream(new FileOutputStream(f));
byte[] buffer = new byte[2048];
int nBytes = 0;
while ((nBytes = in.read(buffer)) > 0) {
out.write(buffer, 0, nBytes);
}
} catch (IOException ioe) {
throw ioe;
} finally {
try {
if (null != out) {
out.flush();
out.close();
}
} catch (IOException ioe) {
throw ioe;
} finally {
if (null != in) {
in.close();
}
}
}
}
}

/**
* 循环创建父目录
*
* @param outFileName
*/
private void makeSupDir(String outFileName) {
//匹配分隔符
Pattern p = Pattern.compile("[" + File.separator + "]");
Matcher m = p.matcher(outFileName);
//每找到一个匹配的分隔符,则创建一个该分隔符以前的目录
while (m.find()) {
int index = m.start();
String subDir = outFileName.substring(0, index);
File subDirFile = new File(subDir);
if (!subDirFile.exists())
subDirFile.mkdir();
}
}

/**
* 递归删除目录及子目录
*
* @param path
*/
private void clean(String path) throws IOException {
File file = new File(path);
//如果该路径不存在
if (!file.exists()) {
System.out.println(path + " Not Exist!");
} else {
//如果是目录,则递归删除
if (file.isDirectory()) {
String[] fileNames = file.list();

if (null == fileNames) {
throw new IOException("IO ERROR While Deleting Files");
}
//如果是空目录则直接删除
else if (fileNames.length == 0) {
file.delete();
} else {
for (String fileName : fileNames) {
File subFile = new File(fileName);
clean(path + File.separator + subFile);
}
System.out.println(file.getAbsolutePath());
//最后删除父目录
file.delete();

}
}
//如果是文件,则直接删除
else {
System.out.println(file.getAbsolutePath());
file.delete();
}
}
}

/**
* 处理安装错误的异常,调用清洗过程
*
* @param outputPath 输出路径
* @throws IOException IO异常
*/
private void dealError(String outputPath) {
//删除已解压的文件
System.out.println("Start Deleting Files......");
try {
clean(outputPath);
System.out.println("Deleting Files OK!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Deleting Files Failed!");
}
}
package com.supcon.supfusion.framework.cloud.i18n.resource.utils;


import com.supcon.supfusion.framework.cloud.common.util.StringExUtil;
import com.supcon.supfusion.framework.cloud.i18n.constants.ResourcesConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
* i18n资源处理操作
* <ul>
* 进程拉起时处理流程 -> process
* <li>读取资源目录</li>
* <li>资源转储临时目录 -> temp</li>
* <li>压缩临时目录 -> compress</li>
* <li>上传至服务器 -> upload</li>
* <li>删除临时目录 -> deleteAnyone</li>
* </ul>
*/
@Slf4j
public class MessageFileUtil {

/********************************************* Process Method ******************************************/

/**
* 上传结束后删除临时目录
* 本地流程的最后一步操作
*
* @param tempDir
* @return
*/
public static Boolean delete(String tempDir) {
try {
tempDir = addFileSeperator(tempDir);
deleteAnyone(tempDir);
} catch (Exception e) {
log.error("delete temp dir fail! ", e);
}
return true;
}

/**
* 处理本地国际化资源目录
*
* @param messageDir
* @param tempDir
* @param modules
* @return
*/
public static String compressBundleMessage(String messageDir, String tempDir, String[] modules) {
URL url = locateUrl(messageDir);
if (null != url) {
String s = url.toString();
if (s.startsWith(ResourcesConstant.JAR_FILE_PREFIX)) {
MessageFileUtil.jarCreateTransform(messageDir, tempDir, modules, url);
} else if (s.startsWith(ResourcesConstant.FILE_PREFIX)) {
MessageFileUtil.fileCreateTransform(tempDir, modules, url);
}
} else {
url = locateUrl("");
//TODO 扫描 指定文件 路径获取资源压缩 若为空 遍历寻找对应jar包,找到对应jar包获取资源压缩
MessageFileUtil.jarsCreateTransform(messageDir, tempDir, modules, url);
}
return tempDir;
}


/**
* 多个模块 遍历每一个 当前jar包内系统中对应文件夹下资源
*/
private static void jarCreateTransform(String messageDir, String tempDir, String[] modules, URL url) {
if (modules != null && modules.length > 0) {
ArrayList<String> localModules = new ArrayList<String>(Arrays.asList(modules));
//循环多个模块 以次压缩每个模块的资源 到临时目录
if (localModules != null && localModules.size() > 0) {
localModules.forEach(module -> {
jarCreate(messageDir, tempDir, module, url);
});
}
}
}

/**
* 多个模块 遍历每一个 文件系统中对应文件夹下资源
*/
private static void fileCreateTransform(String tempDir, String[] modules, URL url) {
if (modules != null && modules.length > 0) {
ArrayList<String> localModules = new ArrayList<String>(Arrays.asList(modules));
//循环多个模块 以次压缩每个模块的资源 到临时目录
if (localModules != null && localModules.size() > 0) {
localModules.forEach(module -> {
fileCreate(tempDir, module, url);
});
}
}
}

/**
* 多个模块 遍历每一个 jar包内的jar包资源
*/
private static void jarsCreateTransform(String messageDir, String tempDir, String[] modules, URL url) {
if (modules != null && modules.length > 0) {
ArrayList<String> localModules = new ArrayList<String>(Arrays.asList(modules));
//循环多个模块 以次压缩每个模块的资源 到临时目录
if (localModules != null && localModules.size() > 0) {
localModules.forEach(module -> {
tempJar(messageDir, tempDir, module, url);
});
}
}
}

/**
* 获取临时目录
*
* @param tempDir
* @return
*/
public static String systemTemp(String tempDir) {
//未设置临时目录,则取系统变量的临时目录
if (StringExUtil.isBlank(tempDir)) {
tempDir = System.getProperty(ResourcesConstant.SYSTEM_TEMP_DIR);
}
return tempDir;
}

/**
* 处理临时文件
*
* @param tempDir
* @return
*/
public static String messageTempPathResolve(String tempDir, String basename) {
//判断临时目录是否设置,未设置则取系统临时目录
tempDir = MessageFileUtil.systemTemp(tempDir);
//添加分隔符
tempDir = MessageFileUtil.addFileSeperator(tempDir);
//添加国际化目录
tempDir += StringExUtil.isNotBlank(basename) ? basename : ResourcesConstant.LOCALE_BASE_NAMES;
//添加系统分隔符,得到完整临时文件目录
tempDir = MessageFileUtil.addFileSeperator(tempDir);
return tempDir;
}

/********************************************* Private Step Method ******************************************/

/**
* 进程拉起时本地流程
*
* @param messageDir
* @param tempDir
* @return
*/
private static File jarCreate(String messageDir, String tempDir, String module, URL url) {
StringBuffer moduleDir = new StringBuffer(messageDir);
moduleDir.append(module);
File file = temp(moduleDir.toString(), tempDir, module, url);
File compressFile = compress(file, tempDir, module);
return compressFile;
}

/**
* 压缩国际化资源目录
*
* @param tempDir
* @param module
* @param url
* @return
*/
private static File fileCreate(String tempDir, String module, URL url) {
try {
File tempFile = new File(url.toURI());
MessageFileUtil.tempDir(tempDir);
String moduleDirPath = tempFile.getAbsolutePath();
StringBuffer moduleDir = new StringBuffer(moduleDirPath);
addFileSeperator(moduleDir);
moduleDir.append(module);
addFileSeperator(moduleDir);
File file = new File(moduleDir.toString());
File compressFile = compress(file, tempDir, module);
return compressFile;
} catch (URISyntaxException ex) {
log.error(ex.getMessage(), ex);
}
return null;
}

/**
* 读取i18n资源目录,写入临时文件目录
* 暂不支持jar包以外的打包方式
*
* @param messageDir
* @param tempDir
*/
private static File temp(String messageDir, String tempDir, String module, URL url) {
File file = null;
try {
tempDir = addFileSeperator(tempDir);
tempDir += module;
file = resolveTempFilesJar(messageDir, tempDir, url);
} catch (IOException e) {
log.error(e.getMessage());
}
return file;
}

/**
* 读取i18n资源目录,写入临时文件目录
* 暂不支持jar包以外的打包方式
*
* @param messageDir
* @param tempDir
* @return
*/
private static void tempJar(String messageDir, String tempDir, String module, URL url) {
try {
String jarPath = url.toString().substring(0, url.toString().indexOf(ResourcesConstant.JAR_FILE_SUFFIX) + ResourcesConstant.JAR_FILE_SUFFIX_LENGTH);
URL jarURL = new URL(jarPath);
JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection();
JarFile jarFile = jarCon.getJarFile();
if (null != jarFile) {
File temp = tempDir(tempDir);
if (temp.exists()) {
Enumeration<JarEntry> jarEntrys = jarFile.entries();
while (jarEntrys.hasMoreElements()) {
JarEntry entry = jarEntrys.nextElement();
String name = entry.getName();
if (name.endsWith(ResourcesConstant.JAR_PACKAGE_SUFFIX) &&
name.contains(ResourcesConstant.LOCALE_BASE_JAR) &&
!entry.isDirectory()
&& name.contains(module)) {
resolveTempFilesJarNest(messageDir, tempDir, module, name);
}
}
}
}
} catch (IOException e) {
log.error(e.getMessage());
}
}

private static void resolveTempFilesJarNest(String messageDir, String tempDir, String module, String name) throws IOException {
writeAndClose(name, tempDir);
String jarName = (ResourcesConstant.JAR_FILE_PREFIX + ResourcesConstant.FILE_PREFIX + ResourcesConstant.LOCALE_URL_SUFFIX +
tempDir + name + ResourcesConstant.JAR_FILE_SUFFIX).replace(ResourcesConstant.LOCALE_URL_PREFIX, ResourcesConstant.LOCALE_URL_SUFFIX);
URL url = null;
try {
url = new URL(jarName);
} catch (MalformedURLException e) {
log.error(e.getMessage());
}
File file = resolveTempFilesJar(messageDir, tempDir, url);
compress(file, tempDir, module);
}

/**
* 压缩文件
*
* @param tempFile
* @return
*/
private static File compress(File tempFile, String tempDir, String module) {
if (tempFile.exists()) {
StringBuffer zipFilePath = new StringBuffer(tempDir);
addFileSeperator(zipFilePath);
zipFilePath.append(module).append(ResourcesConstant.ZIP_FILE_SUFFIX);
return CompressUtil.createZip(tempFile, zipFilePath.toString());
}
return null;
}

/**
* 读取jar包内的目录
* 输出到临时目录
*
* @param messageDir
* @param tempDir
* @param url
* @return
*/
private static File resolveTempFilesJar(String messageDir,
String tempDir,
URL url)
throws IOException {
String jarPath = url.toString().substring(0,
url.toString().indexOf(ResourcesConstant.JAR_FILE_SUFFIX)
+ ResourcesConstant.JAR_FILE_SUFFIX_LENGTH);
URL jarURL = new URL(jarPath);
JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection();
JarFile jarFile = jarCon.getJarFile();
if (null != jarFile) {
File temp = tempDir(tempDir);
if (temp.exists()) {
Enumeration<JarEntry> jarEntrys = jarFile.entries();
while (jarEntrys.hasMoreElements()) {
JarEntry entry = jarEntrys.nextElement();
String name = entry.getName();
if (name.startsWith(messageDir) && !entry.isDirectory()) {
writeAndClose(name, tempDir);
}
}
return temp;
}
}
return null;
}

/**
* 创建临时目录
*
* @param tempDir
* @return
*/
private static File tempDir(String tempDir) {
File temp = new File(tempDir);
if (!temp.exists()) {
temp.mkdirs();
}
return temp;
}

/**
* 写入临时文件
*
* @param inputFileFullName
* @param tempDir
* @throws IOException
*/
private static void writeAndClose(String inputFileFullName, String tempDir) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = locateStream(inputFileFullName);
outputStream = output(tempDir, inputFileFullName);
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
for (int i = 0; i < read; i++) {
outputStream.write(bytes[i]);
}
}
} catch (IOException e) {
log.error("write temp file fail! ", e);
} finally {
try {
if (null != inputStream) {
inputStream.close();
}
if (null != outputStream) {
outputStream.close();
}
} catch (IOException e) {
log.error("close stream fail! ", e);
}

}
}

/**
* 创建输出流
*
* @param tempDir
* @param fileName
* @return
* @throws IOException
*/
private static OutputStream output(String tempDir, String fileName) throws IOException {
OutputStream outputStream;
StringBuffer sb = new StringBuffer(tempDir);
addFileSeperator(sb);
sb.append(fileName);
File file = new File(sb.toString());
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
outputStream = new FileOutputStream(file);
return outputStream;
}

/**
* 补目录分隔符
*
* @param dir
* @return
*/
public static String addFileSeperator(String dir) {
if (!dir.endsWith(File.separator)) {
dir += File.separator;
}
return dir;
}

/**
* 补目录分隔符
*
* @param sb
* @return
*/
public static StringBuffer addFileSeperator(StringBuffer sb) {
if (!sb.toString().endsWith(File.separator)) {
sb.append(File.separator);
}
return sb;
}


/**
* 删除目录下的所有文件
*
* @param dirName
*/
private static void deleteAnyone(String dirName) {
File file = new File(dirName);
if (file.exists()) {
if (file.isFile()) {
deleteFile(dirName);
} else {
deleteDir(dirName);
}
}
}

/**
* 删除文件
*
* @param fileName
*/
private static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.exists() && file.isFile()) {
file.delete();
}
}

/**
* 删除目录
*
* @param dirName
*/
private static void deleteDir(String dirName) {
dirName = addFileSeperator(dirName);
File file = new File(dirName);
if (file.exists() && file.isDirectory()) {
if (file.listFiles() != null && file.listFiles().length > 0) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteAnyone(files[i].getAbsolutePath());
}
}
file.delete();
}
}

/**
* 加载资源目录
*
* @param resourcesPath
* @return
*/
private static URL locateUrl(String resourcesPath) {
URL url = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (null != loader) {
url = loader.getResource(resourcesPath);
}
if (null == url) {
url = ClassLoader.getSystemResource(resourcesPath);
}
return url;
}

/**
* 创建输入流
*
* @param fileName
* @return
*/
private static InputStream locateStream(String fileName) {
InputStream inputStream = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (null != loader) {
inputStream = loader.getResourceAsStream(fileName);
}
if (null == inputStream) {
inputStream = ClassLoader.getSystemResourceAsStream(fileName);
}
return inputStream;
}

}

}