Java 使用Jalopy格式化美化代码,格式化美化代码片段
发布时间:2018-04-07作者:laosun阅读(2380)
Jalopy 是一个 Java 源代码格式化工具,它可以使用一套可配置的布局规则修改 Java 源代码的布局。
看到很多java、css、js或者xml的在线美化工具,一直很纳闷,他们是怎么做的,找了一圈,找到这么一个开源的格式化工具 - Jalopy。但是我也只是刚刚开始研究,还没有正式看完,所以还有待优化。目前就简单的写了一个demo。public class javaPreJalopy {
public static String formatJava(String content){
if(StringUtils.isEmpty(content)){
return null;
}
StringBuffer sb = new StringBuffer();
BufferedReader reader = null;
String filePath = Property("user.dir")+"/abcdefg.java";
File file = new File(filePath);
try {
if (!ists()) {
}
Jalopy jalopy = new Jalopy();
InputStream is = new Bytes("UTF-8"));
jalopy.setInput(is, filePath);
jalopy.setOutput(file);
jalopy.format();
if (State() == Jalopy.State.OK) {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = adLine()) != null) {
sb.append(tempString).append("n");
}
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
file.delete();
}
return sb.toString();
}
public static void main(String[] args) {
String content = "class FreshJuice { enum FreshJuiceSize{ SMALL, MEDIUM , LARGE }"
+ " FreshJuiceSize size; } public class FreshJuiceTest { public static vo"
+ "id main(String []args){ FreshJuice juice = new FreshJuice();"
+ " juice.size = FreshJuice.FreshJuiceSize.MEDIUM ; } }";
String result = formatJava(content);
System.out.println(result);
}
}
运行结果:
class FreshJuice {
FreshJuiceSize size;
enum FreshJuiceSize {SMALL,
MEDIUM,
LARGE;
}
}
public class FreshJuiceTest {
public static void main(String[] args) {
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice.FreshJuiceSize.MEDIUM;
}
}
代码就是随便找了一段,请勿特别重视。
下边是文档中给出的方法.
// create a new Jalopy instance with the currently active code convention settings
Jalopy jalopy = new Jalopy();
File file = ...;
// specify input and output target
jalopy.setInput(file);
jalopy.setOutput(file);
// format and overwrite the given input file
jalopy.format();
if (State() == Jalopy.State.OK)
System.out.println(file + " successfully formatted");
else if (State() == Jalopy.State.WARN)
System.out.println(file + " formatted with warnings");
else if (State() == Jalopy.State.ERROR)
System.out.println(file + " could not be formatted");
// setup a destination directory
File destination = ...;
jalopy.setDestination(destination);
jalopy.setInput(file);
jalopy.setOutput(file);
// format the given input file and write the output to the given destination,
// the package structure will be retained automatically
jalopy.format();
...
从这段代码可以看出,Jalopy的格式化需要借助本地file文件,目前还没有找到直接在内存中完成美化的好方法!
敬请关注博主这篇文章!
4 +1
版权声明
分享到:
发表评论
请文明留言
发表
共 0 条评论
本文发布于:2024-02-02 22:59:49,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170688598947016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |