编写一个java程序来删除同一个java程序中的注释?

发布于 2025-01-03 21:04:57 字数 235 浏览 1 评论 0原文

我正在编写一个java程序来删除同一个java程序中的注释。 我正在考虑使用文件阅读器。但我不确定它是否会起作用。

因为两个进程将使用同一个文件。 但我认为在执行代码之前,java文件会创建一个.class文件。 因此,如果我使用 filereader 来编辑 java 文件。它不应该给我错误:另一个进程已经在使用该文件。

我的想法正确吗?

提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

巴黎盛开的樱花 2025-01-10 21:04:57

是的,您可以毫无问题地做到这一点。

注意:请小心以下事项:

String notAComment  = "// This is not a comment"; 

Yes, you can do that without any problems.

Note: Be careful with things like:

String notAComment  = "// This is not a comment"; 
赴月观长安 2025-01-10 21:04:57

如果您只想从 Java 程序中删除注释,为什么不使用正则表达式进行简单的搜索和替换,并将所有注释转换为空字符串呢?

这是在 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);    
    }    

}    

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);    
    }    

}    
ぺ禁宫浮华殁 2025-01-10 21:04:57

你是对的,这不是两个进程使用同一个文件,你的程序将使用 .class 文件并处理 .java 文件。您可能想仔细查看此页面:
使用正则表达式在源代码中查找注释

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

三寸金莲 2025-01-10 21:04:57

是的,使用 FileReader 就可以了。如果您可能有非英语字符或跨不同平台工作,需要注意的一件事是 FileEncoding。在 Eclipse 和其他 IDE 中,您可以将 Java 源文件的字符集更改为不同的编码。如果不确定,可能值得使用:

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

同样,当您将输出写回时,请使用带有 UTF-8 的 OutputStreamWriter。

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.

沩ん囻菔务 2025-01-10 21:04:57

查看帖子从字符串中删除评论来完成你的工作。您可以使用 FileReaderjava.util.Scanner 类来读取文件。

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.

扶醉桌前 2025-01-10 21:04:57

虽然已经晚了,但它可能会帮助一些人删除所有类型的评论。

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;
    }

}

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;
    }

}
终难愈 2025-01-10 21:04:57

为此,我制作了一个开源库(GitHub上的CommentRemover),您可以删除单行和多行Java 评论。

它支持删除或不删除 TODO。
它还支持 JavaScript、HTML、CSS、Properties、JSP 和 XML Comments。

小代码片段如何使用它(有两种类型的用法):

第一种方式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();        
  }

第二种方式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();        
  }

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();        
  }
晨曦÷微暖 2025-01-10 21:04:57

公共类复制{

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();
        }
    }
}

}

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();
        }
    }
}

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文