0

I am Writing a java program to remove the comments in the same java program. I am thinking of using a file reader. But I'm not sure whether it will work.

Because two process will be using the same file. But I think before executing the code, java file will make a .class file. So if I use a filereader to edit the java file. It should not give me error that another process is already using this file.

Am I thinking correct?

Thanks in advance.

vikiiii
  • 9,246
  • 9
  • 49
  • 68

8 Answers8

7

Yes, you can do that without any problems.

Note: Be careful with things like:

String notAComment  = "// This is not a comment"; 
Paul
  • 139,544
  • 27
  • 275
  • 264
6

If you just want to remove comments from a Java program, why don't you do a simple search and replace using a regex, and convert all comments into an empty string?

Here's a verbose way of doing it, in Java:

import java.io.File;    
import java.io.FileReader;    
import java.io.IOException;    
import java.io.BufferedReader;    

class Cleaner{    

    public static void main( String a[] )    
    {    
        String source = readFile("source.java");    

        System.out.println(source.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)",""));    

    }    


    static String readFile(String fileName) {    

        File file = new File(fileName);    

        char[] buffer = null;    

        try {    
                BufferedReader bufferedReader = new BufferedReader( new FileReader(file));    

                buffer = new char[(int)file.length()];    

                int i = 0;    
                int c = bufferedReader.read();    

                while (c != -1) {    
                    buffer[i++] = (char)c;    
                    c = bufferedReader.read();    
                }    

        } catch (IOException e) {    
            e.printStackTrace();    
        }    

        return new String(buffer);    
    }    

}    
sebastian
  • 4,914
  • 2
  • 21
  • 21
  • can you help me understand one line source.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)","") – vikiiii Feb 09 '12 at 08:23
  • 1
    Decompose the regex into () groups so it's easier to understand. ?:/\\* (?:[^*]|(?:\\*+[^*/]))* \\*+/)|(?://.*)","" matches anything like this: (starting with / followed by * (escaped: \*) (followed by zero or more of the following either any char except new line zero or more times or (\* one or more times followed by any string except */) ) this inner pattern 0 or more times followed by \* one or more times followed by / ) OR (starting with // followed by any char except new line ) replace any matches by "" – sebastian Feb 09 '12 at 14:21
  • 3
    Thanks Bastiano9..But this code removes this code also String notAComment = "// This is not a comment"; – vikiiii Feb 10 '12 at 04:13
  • This will not work if a String contains //, for example "Hello //world". – Ventrue Feb 27 '21 at 11:47
2

You are right, the are not two processes using the same file, your program will use the .class files and process the .java files. You may want to take a closer look at this page: Finding Comments in Source Code Using Regular Expressions

Thor
  • 6,607
  • 13
  • 62
  • 96
2

Yes, using a FileReader will work. One thing to watch out is the FileEncoding if you might have non-English characters or work across different platforms. In Eclipse and other IDEs you can change the character set for a Java source file to different encodings. If unsure, it might be worth using:

InputStream in = ....    
BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8"));
..

and likewise when you are writing the output back out, use an OutputStreamWriter with UTF-8.

Paul Jowett
  • 6,513
  • 2
  • 24
  • 19
1

Its late but it may help some to remove all types of comments.

package com.example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
class CommentRemover {

    public static void main(String a[]) {
        File file = new File("F:/Java Examples/Sample.java");
        String fileString = readLineByLine(file);
        fileString = fileString.replaceAll(
                "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)", "");
        System.out.println(fileString);

    }

    private static String readLineByLine(File file) {
        String textFile = "";
        FileInputStream fstream;
        try {
            fstream = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    fstream));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                textFile = textFile + replaceComments(strLine) + "\n";

            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return textFile;
    }

    private static String replaceComments(String strLine) {

        if (strLine.startsWith("//")) {
            return "";
        } else if (strLine.contains("//")) {
            if (strLine.contains("\"")) {
                int lastIndex = strLine.lastIndexOf("\"");
                int lastIndexComment = strLine.lastIndexOf("//");
                if (lastIndexComment > lastIndex) { // ( "" // )
                    strLine = strLine.substring(0, lastIndexComment);
                }
            } else {
                int index = strLine.lastIndexOf("//");
                strLine = strLine.substring(0, index);
            }
        }

        return strLine;
    }

}
rns
  • 1,047
  • 10
  • 25
1

Have a look at the post Remove comments from String for doing your stuff. You may use either FileReader or java.util.Scanner class to read the file.

Community
  • 1
  • 1
Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73
0

I made a open source library (CommentRemover on GitHub) for this necessity , you can remove single line and multiple line Java Comments.

It supports remove or NOT remove TODO's.
Also it supports JavaScript , HTML , CSS , Properties , JSP and XML Comments too.

Little code snippet how to use it (There is 2 type usage):

First way InternalPath

 public static void main(String[] args) throws CommentRemoverException {

 // root dir is: /Users/user/Projects/MyProject
 // example for startInternalPath

 CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
        .removeJava(true) // Remove Java file Comments....
        .removeJavaScript(true) // Remove JavaScript file Comments....
        .removeJSP(true) // etc.. goes like that
        .removeTodos(false) //  Do Not Touch Todos (leave them alone)
        .removeSingleLines(true) // Remove single line type comments
        .removeMultiLines(true) // Remove multiple type comments
        .startInternalPath("src.main.app") // Starts from {rootDir}/src/main/app , leave it empty string when you want to start from root dir
        .setExcludePackages(new String[]{"src.main.java.app.pattern"}) // Refers to {rootDir}/src/main/java/app/pattern and skips this directory
        .build();

 CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
                  commentProcessor.start();        
  }

Second way ExternalPath

 public static void main(String[] args) throws CommentRemoverException {

 // example for externalInternalPath

 CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
        .removeJava(true) // Remove Java file Comments....
        .removeJavaScript(true) // Remove JavaScript file Comments....
        .removeJSP(true) // etc..
        .removeTodos(true) // Remove todos
        .removeSingleLines(false) // Do not remove single line type comments
        .removeMultiLines(true) // Remove multiple type comments
        .startExternalPath("/Users/user/Projects/MyOtherProject")// Give it full path for external directories
        .setExcludePackages(new String[]{"src.main.java.model"}) // Refers to /Users/user/Projects/MyOtherProject/src/main/java/model and skips this directory.
        .build();

 CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
                  commentProcessor.start();        
  }
Ertuğrul Çetin
  • 5,131
  • 5
  • 37
  • 76
-1

public class Copy {

void RemoveComments(String inputFilePath, String outputFilePath) throws FileNotFoundException, IOException {
    File in = new File(inputFilePath);
    File out = new File(outputFilePath);
    BufferedReader bufferedreader = new BufferedReader(new FileReader(in));
    PrintWriter pw = new PrintWriter(new FileWriter(out));
    String line = null, lineToRemove = null;
    while ((line = bufferedreader.readLine()) != null) {
        if (line.startsWith("/*") && line.endsWith("*/")) {
            lineToRemove = line;
        }
        if (!line.trim().equals(lineToRemove)) {
            pw.println(line);
            pw.flush();
        }
    }
}

}

fiddle
  • 1,095
  • 5
  • 18
  • 33