WordCount

https://gitee.com/Siy1015/WordCount

 

代码实现

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class WordCount {
private int charCount;
private int wordCount;
private int lineCount;
 
 
 
public WordCount(int charCount,int wordCount,int lineCount){
this.charCount=charCount;
this.wordCount=wordCount;
this.lineCount=lineCount;
}
//get和set方法
public int getCharCount() {
return charCount;
}
public void setCharCount(int charCount) {
this.charCount = charCount;
}
public int getWordCount() {
return wordCount;
}
public void setWordCount(int wordCount) {
this.wordCount = wordCount;
}
 
public int getLineCount() {
return lineCount;
}
public void setLineCount(int lineCount) {
this.lineCount = lineCount;
}
//main
public static void main(String[] args) throws IOException{
WordCount WC=new WordCount(0,0,0);
String inputFile="file.c";//初始化输入文件名
String outputFile="result.txt";//输出文件
for(int i=0;i<args.length;i++){
if(args[i].endsWith(".c"))
inputFile=args[i];
 
if(args[i].equals("-o"))
outputFile=args[i+1];
}
 
WC.wc(inputFile);
 
for(int i=0;i<args.length;i++)
{
switch(args[i]){
case "-c":{
System.out.println(inputFile+",字符数:" + WC.getCharCount());
break;
}
case "-w":{
System.out.println(inputFile+",单词数:" + WC.getWordCount());
break;
}
case "-l":{
System.out.println(inputFile+",行数:" + WC.getLineCount());
break;
}
case "-o":{
String outTxt="";
for(int j=0;j<args.length;j++){
if(args[j].equals("-c"))
outTxt=outTxt+"\r\n"+inputFile+",字符数:" + WC.getCharCount();
if(args[j].equals("-w"))
outTxt=outTxt+"\r\n"+inputFile+",单词数:" + WC.getWordCount();
if(args[j].equals("-l"))
outTxt=outTxt+"\r\n"+inputFile+",行数:" + WC.getLineCount();
}
// 新建一个txt文件
File outputName = new File(outputFile);
outputName.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(outputName));
out.write(outTxt);
out.flush();
out.close();
break;
}
}
}
}
 
//统计操作
public void wc(String inputFile) throws IOException{
String lineString = null;
String[] buffer;
File dir=new File(inputFile);
BufferedReader bf = new BufferedReader(new FileReader(dir)); // 读取文件
while((lineString=bf.readLine())!=null){
buffer=lineString.split(",| "); //遇到,空格就结束
for(int i=0;i<buffer.length;i++){
if(!buffer[i].equals(""))
wordCount++;
}
lineCount++;
charCount+=lineString.length();
}
bf.close();
}
}
 
文件内容
测试结果

 

 
posted @ 2018-09-24 22:49  Siy1015  阅读(90)  评论(0编辑  收藏  举报