一、代码地址:https://gitee.com/cainiaoY/WordCount

二、代码:

import java.io.*;
import java.util.regex.*; public class wcFuction {
private BufferedReader br;
//文件词统计函数
int getwordnumber(String filename) throws IOException {
int num=0;
String[] strword = null;
File file = new File(filename);
if(file.exists()) {
//读取文件
FileReader fr = new FileReader(filename);
br = new BufferedReader(fr);
String line = null;
StringBuffer sbf = new StringBuffer();
while((line=br.readLine())!= null) {
sbf.append(line);
String str = sbf.toString();
//正则表达式替换符号
str = str.replaceAll("[\\p{Nd}\\u9fa5-\\uffe5\\p{Punct}\\s&&[^-]]", " ");
//按空格将内容分割
strword = str.split("\\s+");
num=strword.length;
}
br.close();
fr.close();
}else {
System.out.println("文件不存在,请重新输入文件!");
}
return num;
}
//文件字符统计函数
int getCharacternumber(String filename) throws IOException {
int number = 0;
String[] strword = null;
File file = new File(filename);
if(file.exists()) {
//读取文件
FileReader fr = new FileReader(filename);
br = new BufferedReader(fr);
String line = null;
String str=null;
StringBuffer sbf = new StringBuffer();
while((line=br.readLine())!= null) {
sbf.append(line);
str = sbf.toString();
strword = str.split("\\s+");
}
for(int i=0;i<strword.length;i++) {
Pattern pattern = Pattern.compile("[0-9a-zA-Z]*");
Matcher matcher = pattern.matcher(strword[i]);
if(matcher.find()) {
number+=matcher.regionEnd();
}
}
br.close();
fr.close();
}else {
System.out.println("文件不存在,请重新输入文件!");
}
return number;
}
//文件行数统计函数
int getlinenumber(String filename) throws IOException {
int linenum = 0;
File file = new File(filename);
if(file.exists()) {
//读取文件
FileReader fr = new FileReader(filename);
//读取文件行数
LineNumberReader lnr = new LineNumberReader(fr);
while(lnr.readLine()!= null) {
linenum=lnr.getLineNumber();
}
lnr.close();
fr.close();
}else {
System.out.println("文件不存在,请重新输入文件!");
}
return linenum;
}
}
import java.io.IOException;
import java.util.Scanner; public class wcTest
{
private static Scanner scanner;
public static void main(String[] args) throws IOException
{
String str = null;
wcFuction wcf = new wcFuction();
//循环询问命令输入
while(true)
{
System.out.print("请输入命令:");
//命令输入
scanner = new Scanner(System.in);
if(scanner.hasNext())
{
str=scanner.nextLine();
}
//分割命令,第一个作为判断第二个为文件路径
String[] strword = str.split(" ");
if(strword.length==2)
{
if(strword[0].equals("-c"))
{
int chara=wcf.getCharacternumber(strword[1]);
System.out.println("该文件的字符数:"+chara);
}
else if(strword[0].equals("-w"))
{
int word=wcf.getwordnumber(strword[1]);
System.out.println("该文件的词数:"+word);
}
else if(strword[0].equals("-l"))
{
int line=wcf.getlinenumber(strword[1]);
System.out.println("该文件的行数:"+line);
}
else
{
if(strword[0].equals("end"))
{
break;
}
else
{
System.out.println("命令输入错误,请重新输入!");
}
}
}
}
}
}

三、截图

WordConut-LMLPHP

WordConut-LMLPHP

WordConut-LMLPHP

WordConut-LMLPHP

WordConut-LMLPHP

05-07 15:11