Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写java程序以删除同一java程序中的注释?_Java_Process - Fatal编程技术网

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

编写java程序以删除同一java程序中的注释?,java,process,Java,Process,我正在编写一个java程序来删除同一java程序中的注释。 我正在考虑使用文件阅读器。但我不确定它是否会起作用 因为两个进程将使用同一个文件。 但我认为在执行代码之前,java文件将生成一个.class文件。 因此,如果我使用filereader编辑java文件。另一个进程已经在使用此文件,这不会给我错误信息 我的想法正确吗 提前谢谢。是的,您可以毫无问题地完成 注意:注意以下事项: String notAComment = "// This is not a comment"; 您是对的

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

因为两个进程将使用同一个文件。 但我认为在执行代码之前,java文件将生成一个
.class
文件。 因此,如果我使用
filereader
编辑java文件。另一个进程已经在使用此文件,这不会给我错误信息

我的想法正确吗


提前谢谢。

是的,您可以毫无问题地完成

注意:注意以下事项:

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

您是对的,不是两个进程使用同一个文件,您的程序将使用
.class
文件并处理
.java
文件。您可能需要仔细查看此页面:

看看这篇文章,看看你在做什么。您可以使用
FileReader
java.util.Scanner
类来读取文件。

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

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

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

如果您只想从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);    
    }    

}    
公共类副本{

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

}

虽然已经很晚了,但是删除所有类型的评论可能会有帮助

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

}
我为此做了一个开源软件,可以删除单行和多行Java注释

它支持删除或不删除TODO。
它还支持JavaScript、HTML、CSS、属性、JSP和XML注释

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

第一条道路

 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();        
  }
 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();        
  }
第二条外部路径

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

一开始不添加评论不是更容易吗?除非您试图隐藏某些内容^o)为什么不使用正则表达式来执行此操作?编写一个Java程序来实现这一点似乎有些过头了。我不知道如何通过正则表达式来实现这一点。它需要使用模式吗?你能帮我理解一行代码吗?replaceAll((?:/\*(?:[^*]|(?:\*+[^*/]))**+/)|(?:/.*),“”)将正则表达式分解成()组,这样更容易理解。?:/\*(?:[^*]|(?:\*+[^*/])*\*+/)|(?:/.*),“”匹配如下内容:(以/后跟*(转义:)(后跟以下零或多个字符,除新行外的任何字符零次或多次,或(*一次或多次后跟除*/)以外的任何字符串)此内部模式0次或多次后跟*一次或多次后跟/)或(以//开头,后跟除新行以外的任何字符)将任何匹配项替换为“”Thank Bastiano9..。但此代码同时删除字符串notAComment=“//这不是注释";如果字符串包含//,例如“Hello//world”,则此操作无效。如何使用您的库?@VedPrakash此处是链接,页面显示了您需要遵循的步骤:谢谢。知道了。