Android文档次数统计——统计文档字符数,行数,单词数
主要代码:
private void analysis() {
String str="";
int words = 0;//单词数
int chars = 0;//字符数
int lines = 0;//行数
String filename=et_name.getText().toString();
FileInputStream fis=null;
BufferedReader br=null;
try {
//判断是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/"+filename+".txt");
if (file.exists()){//判断文件是否存在
fis=new FileInputStream(file);
br=new BufferedReader(new InputStreamReader(fis));
while((str=br.readLine())!=null){
char[] b=str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (b[i]==' '){
spaces++;//空格数
}else if (b[i]==','||b[i]=='.'){
marks++;
}
}
words+=str.split("[ \\.,]").length;
chars+=str.length();//字符串的长度
lines++;//行数
}
character=chars-(spaces+marks);//字母数
br.close();
tv_read.setText("单词数:"+words+",字符数:"+chars+",行数:"+lines+");
}
else {
Toast.makeText(this, "不存在该文件", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
布局代码: