编写一个JAR文件,检单词数量代码
时间: 2024-12-11 14:39:16 浏览: 12
编写一个简单的Java程序来计算文本文件中单词的数量并打包成JAR文件,可以按照以下步骤进行:
1. 首先,创建一个Java类,例如`WordCounter.java`,内容如下:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordCounter {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java WordCounter <filename>");
return;
}
String filename = args[0];
int wordCount = countWordsInFile(filename);
System.out.printf("The file %s contains %d words.\n", filename, wordCount);
}
private static int countWordsInFile(String filePath) {
int count = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
// 分割字符串并忽略标点符号和空格
String[] words = line.toLowerCase().split("\\W+");
for (String word : words) {
if (!word.isEmpty()) {
count++;
}
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return count;
}
}
```
2. 然后,在命令行中编译这个类,生成字节码(`.class`文件):
```
javac WordCounter.java
```
3. 使用`jar`命令打包成JAR文件,假设你的当前目录下有`WordCounter.class`文件:
```
jar cvf wordcounter.jar WordCounter.class
```
4. 运行JAR文件,传入文本文件路径作为参数:
```
java -jar wordcounter.jar yourfile.txt
```
阅读全文