对应的java代码结构如下,适当做了重构,可以在稍后把java代码封装一下。
-
public class FormatSql {
-
-
public static void main(String[] args) throws IOException {
-
-
ArrayList<String> strArr = readFromFile(); //从指定的文件中读取文件内容
-
-
formatSQL(strArr); //格式化sql文件
-
-
OutputFormatSql(strArr); //输出格式化后的sql语句
-
-
}
完整的代码如下:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FormatSql {
public static void main(String[] args) throws IOException {
ArrayList<String> strArr = readFromFile();
formatSQL(strArr);
OutputFormatSql(strArr);
}
private static void formatSQL(ArrayList<String> strArr) {
String tmpCurrLine;
String tmpNextLine;
for (int i = 0; i < strArr.size(); i++) {
tmpCurrLine = strArr.get(i);
// consider last line
if (strArr.size() == (i + 1)) {
tmpNextLine = "";
} else {
tmpNextLine = strArr.get(i + 1);
formatSqlLine(tmpCurrLine, tmpNextLine, strArr, i);
}
}
}
private static void OutputFormatSql(ArrayList<String> strArr) {
for (int i = 0; i < strArr.size(); i++) {
System.out.println(strArr.get(i));
}
}
private static void formatSqlLine(String tmpCurrLine, String tmpNextLine,
ArrayList<String> strArr, int i) {
String tmpCurrFormatLine;
String tmpCurrLeftLine;
for (int j = tmpCurrLine.length() - 1; j > 0;) {
if (tmpCurrLine.charAt(j) == ‘ ‘) {
tmpCurrFormatLine = tmpCurrLine.substring(0, j);
tmpCurrLeftLine = tmpCurrLine.substring(j + 1, tmpCurrLine
.length()); // keep last space
strArr.set(i, tmpCurrFormatLine);
strArr.set(i + 1, tmpCurrLeftLine + tmpNextLine);
tmpNextLine = tmpCurrLeftLine + tmpNextLine;
// System.out.println(tmpCurrFormatLine);
// System.out.println(tmpCurrLeftLine);
// System.out.println(tmpNextLine);
break;
} else {
j--;
}
}
}
private static ArrayList<String> readFromFile()
throws FileNotFoundException, IOException {
ArrayList<String> strArr = new ArrayList<String>();
FileReader reader = new FileReader("c://a.sql");
BufferedReader br = new BufferedReader(reader);
String str = null;
while ((str = br.readLine()) != null) {
strArr.add(str);
}
br.close();
reader.close();
return strArr;
}
}