要求:给定一份txt文件,读取文件的行数,单词数,字符数(包括空格和标点符号)以及查阅某一单词在文件中出现的次数。
- 读取文件的行数
public static void ReadFile() throws FileNotFoundException,IOException{
//读取文件的行数
int count_line=0;
File file = new File(filepath);
FileInputStream filelines = new FileInputStream(file);
Scanner input = new Scanner(filelines);
while(input.hasNextLine()){
input.nextLine();
count_line++;
}
System.out.println("该文本文件的行数为:" + count_line);
input.close();
}
- 统计文件的单词数量
public static void WordNumber() throws IOException {
//读取文件的单词数
FileReader file = new FileReader(filepath);
int x = file.read();
int wordnumber = 0;
while(x != -1) {
if( (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') ) {
wordnumber++;
x = file.read();
while((x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z')) {
x = file.read();
}
}
else
x = file.read();
}
file.close();
System.out.println("该文本中的单词个数是:" + wordnumber);
}
- 统计文件的字符数
public static void CharacterNumebr() throws IOException{
FileReader file = new FileReader(fiepath);
BufferedReader in = new BufferedReader(file);
String str = null;
int character = 0;
while((str = in.readLine()) != null) {
character += str.length();
}
in.close();
System.out.println("该文件的总字符数为:" + character);
}
- 统计给定字母在文本中出现的次数
public static void LetteNumber() throws IOException{
FileReader file = new FileReader(filepath);
BufferedReader in = new BufferedReader(file);
StringBuffer strb = new StringBuffer();
Scanner input = new Scanner(System.in);
System.out.println("请输入需要查询的字母:");
String key = input.next();
char s = key.charAt(0);
if((s >= 'A' && s <= 'Z') || (s >= 'a' && s <= 'z')) {
while(true) {
String line = in.readLine();
if(line == null)
break;
strb.append(line);
}
String result = strb.toString();
int count = 0;
int index = 0;
while(true) {
index = result.indexOf(key,index + 1);
if(index > 0)
count ++;
else
break;
}
input.close();
in.close();
System.out.println(key + "一共出现了" + count + "次");
}
else
System.out.println("您的输入为特殊字符,请重新输入!");
}
}