|
1 | 1 | package io.github.fvarrui.javapackager.utils; |
2 | 2 |
|
3 | | -import static io.github.fvarrui.javapackager.utils.CommandUtils.execute; |
4 | | - |
5 | 3 | import java.nio.charset.Charset; |
6 | 4 | import java.nio.charset.StandardCharsets; |
7 | | -import java.util.regex.Matcher; |
8 | | -import java.util.regex.Pattern; |
9 | 5 |
|
10 | 6 | import org.apache.commons.lang3.SystemUtils; |
11 | 7 |
|
12 | 8 | public class CharsetUtil { |
13 | | - |
| 9 | + |
| 10 | + private static Charset commandLineCharset; |
| 11 | + |
14 | 12 | public static Charset getCommandLineCharset(){ |
15 | | - if (SystemUtils.IS_OS_WINDOWS) { |
16 | | - try{ |
17 | | - String result = execute("cmd", "/k", "chcp"); |
18 | | - String code = find("\\d+", result); |
19 | | - switch (code){ |
20 | | - case "037": return Charset.forName("IBM037"); |
21 | | - case "936": return Charset.forName("gb2312"); |
22 | | - case "950": return Charset.forName("big5"); |
23 | | - case "1145": return Charset.forName("IBM01145"); |
24 | | - case "1200": return StandardCharsets.UTF_16; |
25 | | - case "51936": return Charset.forName("EUC-CN"); |
26 | | - case "65001": return StandardCharsets.UTF_8; |
27 | | - } |
28 | | - } catch (Exception e){ |
29 | | - // do nothing |
30 | | - } |
| 13 | + if (commandLineCharset == null) { |
| 14 | + if (SystemUtils.IS_OS_WINDOWS) { |
| 15 | + commandLineCharset = chcp(); |
| 16 | + } else { |
| 17 | + commandLineCharset = Charset.defaultCharset(); |
| 18 | + } |
31 | 19 | } |
32 | | - return Charset.defaultCharset(); |
| 20 | + return commandLineCharset; |
33 | 21 | } |
34 | | - |
35 | | - private static String find(String pattern,String data){ |
36 | | - Pattern r = Pattern.compile(pattern); |
37 | | - Matcher matcher = r.matcher(data); |
38 | | - matcher.find(); |
39 | | - return matcher.group(); |
| 22 | + |
| 23 | + private static Charset chcp() { |
| 24 | + try{ |
| 25 | + String result = CommandUtils.run("cmd /k chcp"); |
| 26 | + String code = StringUtils.find("\\d+", result); |
| 27 | + Logger.debug("'chcp' code found: " + code); |
| 28 | + switch (code){ |
| 29 | + case "37": |
| 30 | + case "037": return Charset.forName("IBM037"); |
| 31 | + case "936": return Charset.forName("gb2312"); |
| 32 | + case "950": return Charset.forName("big5"); |
| 33 | + case "1145": return Charset.forName("IBM01145"); |
| 34 | + case "1200": return StandardCharsets.UTF_16; |
| 35 | + case "51936": return Charset.forName("EUC-CN"); |
| 36 | + case "65001": return StandardCharsets.UTF_8; |
| 37 | + } |
| 38 | + } catch (Exception e){ |
| 39 | + // do nothing |
| 40 | + } |
| 41 | + return Charset.defaultCharset(); |
40 | 42 | } |
41 | 43 |
|
42 | 44 | } |
0 commit comments