在修改Hibernate Tools的源码的时候,发现的一个java格式化工具类.
|
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 |
Java代码 package org.hibernate.tool.ide.formatting; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.text.edits.TextEdit; import org.hibernate.tool.hbm2x.ExporterException; public class JavaFormatter { private CodeFormatter codeFormatter; /** * @param args */ public static void main(String[] args) { //DefaultCodeFormatter.USE_NEW_FORMATTER = true; HashMap hashMap = new HashMap(); hashMap.put(JavaCore.COMPILER_SOURCE, "1.5"); hashMap.put(JavaCore.COMPILER_COMPLIANCE, "1.5"); hashMap.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5"); final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(hashMap); JavaFormatter format = new JavaFormatter(null); format.formatFile(new File("D:\\workspace\\CodeGenerator\\src\\com\\Table3.java")); } public JavaFormatter(Map settings) { if(settings==null) { // if no settings run with jdk 5 as default settings = new HashMap(); settings.put( JavaCore.COMPILER_SOURCE, "1.5"); settings.put( JavaCore.COMPILER_COMPLIANCE, "1.5"); settings.put( JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5"); } this.codeFormatter = ToolFactory.createCodeFormatter(settings); } /** * Throws exception if not possible to read or write the file. * Returns true if formatting went ok; returns false if the formatting could not finish because of errors in the input. * * @param file * @param codeFormatter * @return */ public boolean formatFile(File file) throws ExporterException { IDocument doc = new Document(); try { String contents = new String(org.eclipse.jdt.internal.compiler.util.Util.getFileCharContent(file, null)); doc.set(contents); TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, contents, 0, contents.length(), 0, null); if (edit != null) { edit.apply(doc); } else { return false; // most likely syntax errror } // write the file final BufferedWriter out = new BufferedWriter(new FileWriter(file)); try { out.write(doc.get()); out.flush(); } finally { try { out.close(); } catch (IOException e) { /* ignore */ } } return true; } catch (IOException e) { throw new ExporterException("Could not format " + file, e); } catch (BadLocationException e) { throw new ExporterException("Could not format " + file, e); } } } |
