作业-- 统计文本文件中的字符数、单词数、行数

用AndroidStudio解析统计文本文件中的字符数、单词数、行数。

代码部分:

package administrator.mc;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
    private EditText editText;
    private Button button;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText=(EditText) findViewById(R.id.editText);
        button=(Button) findViewById(R.id.button);
        textView=(TextView) findViewById(R.id.textView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int charnumber = 0 ;//字符数
                int words = 0;//单词数
                int linenumber = 0;//行数
                String filename=editText.getText().toString();
                try {
                    //打开文件
                    File file=new File (Environment.getExternalStorageDirectory().
                            getCanonicalPath()+"/"+filename+".txt");
                    FileInputStream isr=new FileInputStream(file );
                    BufferedReader br =new BufferedReader(new InputStreamReader(isr));
                    //解析文件
                    while( br.read()!= -1){
                        String s = br.readLine();
                        charnumber+=s.length();
                        words +=s.split(" ").length;
                        linenumber ++;
                    }
                    isr.close();//关闭
                    textView.setText("字符数:"+charnumber+"\t单词数:"+words+"行 数:"+linenumber);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

  运行结果:

记录表:

 

posted @ 2017-03-27 23:01  柚栯  阅读(611)  评论(0编辑  收藏  举报