java编写一个程序读取txt文件内容并输出该txt文件有多少字母
时间: 2024-05-09 14:21:29 浏览: 12
和数字。
好的,这是一个很简单的问题,你可以这样实现:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CountLettersAndDigits {
public static void main(String[] args) {
int count = 0;
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
while ((line = br.readLine()) != null) {
for (char c : line.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
count++;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("The file contains " + count + " letters and digits in total.");
}
}
```
这个程序会读取当前目录下的 `test.txt` 文件,并输出该文件中有多少个字母和数字。
注意,这个程序假设文件中只包含 ASCII 字符。如果文件中包含非 ASCII 字符(例如中文字符),那么需要修改程序来适应该情况。