public static void main(String[] args) throws IOException { if (args.length != 2) { printUsage(); System.exit(-1); }
CommentFilter cf = new CommentFilter(); BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(args[0]))); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(args[1]))); String line = null; while ((line = reader.readLine()) != null) { String filterLine = cf.multiLineCommentFilter(line); if (filterLine.trim().equals("")) continue; writer.write(filterLine); writer.newLine(); } } }
比如:
/*sssfasdf
sss
*/
因为.不能匹配\r\n
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;/**
* @author fisher
*
* <pre>
*
* Title: SQLCommentFilter.java
*
* Description: 删除SQL脚本中的注释
*
* </pre>
*/public class CommentFilter { private boolean inMultiLineComment = false; /**
* Filter out multiLine comments.
*/
private String multiLineCommentFilter(String line) {
StringBuffer buf = new StringBuffer();
int index;
if (inMultiLineComment && (index = line.indexOf("*/")) > -1) {
inMultiLineComment = false;
if (line.length() > index + 2) {
buf.append(inlineCommentFilter(line.substring(index + 2)));
}
return buf.toString();
} else if (inMultiLineComment) {
return "";
} else if ((index = line.indexOf("/*")) > -1) {
inMultiLineComment = true;
buf.append(inlineCommentFilter(line.substring(0, index)));
return buf.toString();
} else {
return inlineCommentFilter(line);
}
} /**
* Filter inline comments
*/
private String inlineCommentFilter(String line) {
if (line == null || line.equals("")) {
return "";
}
return line.replaceAll("--.*", "");
} private static void printUsage() {
System.out.println("Usage:java CommentFilter src_shell_file dest_shell_file");
}
public static void main(String[] args) throws IOException {
if (args.length != 2) {
printUsage();
System.exit(-1);
}
CommentFilter cf = new CommentFilter(); BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(args[0]))); BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(args[1]))); String line = null;
while ((line = reader.readLine()) != null) {
String filterLine = cf.multiLineCommentFilter(line);
if (filterLine.trim().equals(""))
continue;
writer.write(filterLine);
writer.newLine();
}
}
}