java代码⾃动对齐_java程序实现编写代码时变量名垂直对齐的
风格
记录英语单词时,想把英语和中⽂翻译分别对齐,有些⼈写代码喜欢把变量按这种⽅式对齐。在⽹上没搜到相关⽅法,于是⾃⼰试着写代码去实现,原本以为很简单,写的时候才发现有不少问题。先看效果:
普通的
对齐前:
对齐后:
发挥点创意
对齐前:
对齐后:
实现
实现的思路⽐较简单,读取⽂本⽂件,按正则分割,出最长的部分,补齐空格,输出。
看起来相当简单,花了⼀个多⼩时,就写出来了,马上运⾏,发现输出⼀团糟,去查看每个部分的字符数,个数是⼀样的,⽹上⼀搜,原来跟字体有关系,好吧,那换个等宽的字体。换好字体后有些地⽅已经对齐了,有些地⽅还是没对齐,发现是中⽂的问题,中⽂宽度与英⽂宽度不相同,于是⾸先根据正则去判断字符是中⽂还是英⽂,然后⾃⼰实现计算字符长度的⽅法,在判断中⽂字符上折腾了许久,因为标点符号等等都要考虑进去,反正是来来回回试了好久,对Unicode编码范围不熟悉,没办法。终于,好像都搞定了,反复测试,突然发现第⼀⾏的对齐少了⼀个空格,,这是怎么回事啊,Debug发现第⼀⾏的最开始有⼀个奇怪的字符"\uFEFF",这他妈是什么⿁,上⽹搜,发现是Unicode编码的什么BOM头,好吧,不管它是什么⿁,直接把它去掉了……
反正是遇到了各种各样的问题,与字符集相关的问题实在是太头疼了。另外,我没有去处理编码的问题,所以⽂本的编码需要和IDE的编码保持⼀致,否则就会产⽣乱码。
源码
看过《重构》和《代码整洁之道》之后,写代码时时刻想着要写⼲净点,扩展性强点,经过反复修改,最终⾃⼰觉得还⾏吧,当然,肯定有不少值得改进的地⽅,现在就这样吧。
App.java
1 packagetextalign;2
3 importjava.io.IOException;4
9 public classApp {10
11 public static voidmain(String[] args) {12 long start =System.currentTimeMillis();13
14 String filePath = "C:\\Users\\tingl\\Desktop\\";15 TextAlign textAlign = new TextAlign(/*",|。|,|[.]|( {2,})|\t| +"*/);16
17 if (args.length > 0) {18 filePath = args[0];19 }20 try{21 textAlign.align(filePath);22 } catch(IOException e) {23
e.printStackTrace();24 }25
java怎么编写26 System.out.println(System.currentTimeMillis() -start);27 }28 }
TextAlign.java
1 packagetextalign;2
3 importjava.io.IOException;
4 importjava.util.List;
5 Pattern;6
7 /**
8 *@authortingl9 *@version2017/9/2710 */
11 public classTextAlign {12 private static final String CHINESE_CHARACTER = "[\u4e00-\u9fa5]|[\uFE30-\uFFA0]|
[\u3000-\u303F]";13 private static final Pattern CHINESE_CHARACTER_PATTERN
=Patternpile(CHINESE_CHARACTER);14 private static final int SEPARATE_SPACE_AMOUNT = 4;15
16 privateTextAlignFileUtil textAlignFileUtil;17 private ListtextLines;18 private int[] longestBlockLengt
hs;19
20 publicTextAlign() {21 textAlignFileUtil = newTextAlignFileUtil();22 }23
24 publicTextAlign(String spiltRegex) {25 textAlignFileUtil = newTextAlignFileUtil(spiltRegex);26 }27
28 public void align(String filePath) throwsIOException {29 textLines =adToList(filePath);30 initLongestBlockLengths();31 fillTextLinesBySpaces();32 textAlignFileUtil.write();33 }34
35 private voidinitLongestBlockLengths() {36 int longestArrayLength = 0;37 for(String[] blocks : textLines) {38 if (blocks.length >longestArrayLength) {39 longestArrayLength =blocks.length;40 }41 }42 longestBlockLengths = new
int[longestArrayLength];43 fillLongestBlockLengths();44 }45
46 private voidfillLongestBlockLengths() {47 for(String[] blocks : textLines) {48 if (blocks.length < 2) continue;49 for (int i = 0; i < blocks.length; i++) {50 int length =stringLengthFitWidth(blocks[i]);51 if (length >longestBlockLengths[i]) {52 longestBlockLengths[i] =length;53 }54 }55 }56 }57
58 private intstringLengthFitWidth(String s) {59 if (!CHINESE_CHARACTER_PATTERN.matcher(s).find()) {60
returns.length();61 }62 int length = 0;63 for (String c : s.split("")) {64 if(CHINESE_CHARACTER_PATTERN.matcher(c).find()) {65 length++;66 }67 length++;68 }69 returnlength;70 }71
72 private voidfillTextLinesBySpaces() {73 for(String[] blocks : textLines) {74 for (int i = 0; i < blocks.length - 1; i++) {75 String block =blocks[i];76 int spaceAmount = longestBlockLengths[i] - stringLengthFitWidth(block)
+SEPARATE_SPACE_AMOUNT;77 blocks[i] = block +spaces(spaceAmount);78 }79 }80 }81
82 private String spaces(intspaceAmount) {83 StringBuilder spaces = newStringBuilder();84 for (int i = 0; i < spaceAmount; i++) {85 spaces.append(" ");86 }String();88 }89 }
TextAlignFileUtil.java
1 packagetextalign;2
3 import java.io.*;
4 importjava.util.ArrayList;
5 importjava.util.Arrays;
6 importjava.util.List;7
12 classTextAlignFileUtil {13 private static final String FILENAME_POSTFIX = "_aligned";14 private String spiltRegex = "( {2,})|\t";15 private ListtextLines;16 privateString outPath;17
18 TextAlignFileUtil() {19 }20
21 TextAlignFileUtil(String spiltRegex) {22 this.spiltRegex =spiltRegex;23 }24
25 List readToList(String path) throwsIOException {26 File file = newFile(path);27 returnreadToList(file);28 }29
30 private List readToList(File file) throwsIOException {31 AbsolutePath());32 try (BufferedReader reader = new BufferedReader(newFileReader(file))) {33 textLines = new ArrayList<>();34 String line;35 while ((line = adLine()) != null) {36 textLines.add(removeEmptyAndTrim(line.split(spiltRegex)));37 }38 }39 removeBomHead();40 returntextLines;41 }42
43 private voidgetOutPath(String srcPath) {44 int dotPosition = srcPath.lastIndexOf(".");45 outPath = srcPath.substring(0, dotPosition) + FILENAME_POSTFIX +srcPath.substring(dotPosition);46 if (newFile(outPath).exists()) {47
getOutPath(outPath);48 }49 }50
51 privateString[] removeEmptyAndTrim(String[] src) {52 for (int i = 0; i < src.length; i++) {53 src[i] =src[i].trim();54 }55
56 List dest = new ArrayList<>(Arrays.asList(src));veIf(String::isEmpty);58 Array(new
String[0]);59 }60
61 private voidremoveBomHead() {62 String[] blocks = (0);63 blocks[0] = blocks[0].replace("\uFEFF", "");64 }65
66 void write() throwsIOException {67 try (BufferedWriter writer = new BufferedWriter(newFileWriter(outPath))) {68
for(String[] blocks : textLines) {69 writer.write(getLine(blocks));wLine();71 writer.flush();72 }73 }74 }75
76 privateString getLine(String[] blocks) {77 StringBuilder sb = newStringBuilder();78 for(String block : blocks) {79
sb.append(block);80 }String();82 }83 }

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。