java中的删除所有注释
时间: 2023-08-31 07:10:37 浏览: 64
以下是一个简单的Java程序,用于删除Java代码中的所有注释:
```
import java.io.*;
public class RemoveComments {
public static void main(String[] args) throws IOException {
String inputFileName = "inputFile.java";
String outputFileName = "outputFile.java";
BufferedReader reader = new BufferedReader(new FileReader(inputFileName));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName));
String line = reader.readLine();
boolean inBlockComment = false;
while (line != null) {
if (!inBlockComment) {
line = removeLineComments(line);
}
if (line.contains("/*")) {
inBlockComment = true;
line = removeBlockCommentStart(line);
}
if (inBlockComment) {
if (line.contains("*/")) {
inBlockComment = false;
line = removeBlockCommentEnd(line);
} else {
line = "";
}
}
writer.write(line);
writer.newLine();
line = reader.readLine();
}
reader.close();
writer.close();
}
private static String removeLineComments(String line) {
int index = line.indexOf("//");
if (index != -1) {
line = line.substring(0, index);
}
return line;
}
private static String removeBlockCommentStart(String line) {
int index = line.indexOf("/*");
if (index != -1) {
line = line.substring(0, index);
}
return line;
}
private static String removeBlockCommentEnd(String line) {
int index = line.indexOf("*/");
if (index != -1) {
line = line.substring(index + 2);
}
return line;
}
}
```
该程序将从名为“inputFile.java”的文件中读取Java代码,并将删除所有注释后将结果写入名为“outputFile.java”的文件中。
该程序使用三个帮助方法来删除不同类型的注释:
- `removeLineComments`方法删除单行注释(以“//”开头的注释)。
- `removeBlockCommentStart`方法删除块注释的开始部分(以“/*”开头的注释)。
- `removeBlockCommentEnd`方法删除块注释的结束部分(以“*/”结尾的注释)。
该程序还使用一个布尔变量`inBlockComment`来跟踪是否当前正在处理块注释。如果是,则程序将跳过所有行,直到找到块注释的结尾。否则,程序将删除单行注释并处理块注释的开始。
请注意,该程序仅删除Java代码中的注释,并且可能无法正确处理某些情况,例如在字符串或字符字面量中的注释。因此,请谨慎使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)