I always wanted to scna whole folder and remove unwanted comments from my java codings. Here is a method which you can ready made use it to acheive this. I hope that this helps some one. Of course your javac task will remove comments from the class file but having a source file with clean code always makes an impression.
I have a string array of extensions so that this can be used for other types of files also.
If you make the variable boolean changeExt=true; then the file will be overwritten, else a new file will be created with an extension of file.java.changed
import org.apache.commons.io.FileUtils;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
private void findFilesandReplaceComment() {
File rootDir = null;
String[] extensions = { "java" };
boolean recursive = true;
String fileContent=null;
Collection dirFiles = null;
String encoding=null;
Iterator fileIterator = null;
String commentStr=null;
FileOutputStream fout = null;
File inputFile = null;
PrintStream pout = null;
boolean changeExt=true;
String fileExt = null;
try{
encoding="UTF-8";
rootDir=new File("some directory");
commentStr = "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)";
fileIterator = FileUtils.iterateFiles(rootDir, extensions, recursive);
for(;fileIterator.hasNext();){
inputFile = (File) fileIterator.next();
fileContent=FileUtils.readFileToString(inputFile, encoding);
// Open an output stream
if(changeExt == true){
fileExt = inputFile.getName().substring(0,inputFile.getName().indexOf(".java"))+".changed";
}else{
fileExt = "";
}
fout = new FileOutputStream(new File(inputFile.getAbsolutePath()+fileExt));
pout = new PrintStream(fout);
pout.println(fileContent.replaceAll(commentStr, ""));
fout.flush();
fout.close();
pout.flush();
pout.close();
}
}catch (Exception e) {
e.printStackTrace();
}finally{
rootDir = null;
fileContent=null;
dirFiles = null;
encoding=null;
fileIterator = null;
commentStr=null;
fout = null;
inputFile = null;
pout = null;
fileExt = null;
}
}
My Quotes
When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go
THE WORLD SHOULD CRY
Powered by Find-IP.net
Tuesday, April 13, 2010
Find files recursively and remove unwanted comments
Subscribe to:
Post Comments
(
Atom
)
No comments :