作业
首先布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.myapplication2.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文件内容:"
android:textSize="15dp"/>
<EditText
android:inputType="textMultiLine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et_content"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_write"
android:text="保存"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_analysis"
android:text="解析"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_read"
android:textSize="20dp"/>
</LinearLayout>
定义属性
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et_content;
private Button btn_show;
private Button btn_analysis;
private TextView tv_read;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
et_content = (EditText) findViewById(R.id.et_content);
btn_show = (Button) findViewById(R.id.btn_show);
btn_analysis = (Button) findViewById(R.id.btn_analysis);
tv_read = (TextView) findViewById(R.id.tv_read);
btn_show.setOnClickListener(this);
btn_analysis.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_show:
show();
break;
case R.id.btn_analysis:
analysis();
break;
}
}
解析文档
private void analysis() {
String st = "";
int words=0;//单词数
int chars=0;//字符数
int lines=0;//行数
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/test.txt");
// 打开文件输入流
FileInputStream fir = new FileInputStream(file);
BufferedReader reads = new BufferedReader(new InputStreamReader(fir));
while ((st = reads.readLine()) != null) {
words+=st.split("[ \\.,?]").length;//用于把一个字符串分割成字符串数组,字符串数组的长度,就是单词个数
chars+=st.length();//字符串的长度,即字符数
lines++;//行数(由于每次读取一行,行数自加即可)
}
fir.close();
tv_read.setText("单词数:"+words+",字符数:"+chars+",行数:"+lines);
}
} catch (Exception e) {
e.printStackTrace();
}
}
得到结果