WordCount
Posted wajp
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WordCount相关的知识,希望对你有一定的参考价值。
1.项目地址:https://gitee.com/wajp/WordCount
2.代码:
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; } 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+" "+inputFile+",字符数:" + WC.getCharCount(); if(args[j].equals("-w")) outTxt=outTxt+" "+inputFile+",单词数:" + WC.getWordCount(); if(args[j].equals("-l")) outTxt=outTxt+" "+inputFile+",行数:" + WC.getLineCount(); } 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(); } }
3.测试
4.参考文献链接
【1】http://www.cnblogs.com/xinz/p/5044037.html
【2】https://www.jianshu.com/p/5323bca00825
以上是关于WordCount的主要内容,如果未能解决你的问题,请参考以下文章