本次作业是解析一个文件,我们要解析一个文件首先要能获取打开它,或者是自己创建一个文件。但是我没有做到只能获取edittext控件中输入的文字进行简单解析,这和本次作业的目地有本质的差别。
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.et);
button = (Button)findViewById(R.id.btj);
textView = (TextView)findViewById(R.id.tvs);
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+" 单词数:"+words+"行 数:"+linenumber);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
运行结果
我在网上找到了保存文件的的方法,但是我把它放进我的程序时没有反应,经过很多次的修改调试还未解决。。。。
以下是我在网上找的保存文件的方法
private void write() {
String txt = editText.getText().toString();
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File sdDire = Environment.getExternalStorageDirectory();
FileOutputStream outFileStream = new FileOutputStream(sdDire.getCanonicalPath() + "/test.txt");
outFileStream.write(txt.getBytes());
outFileStream.close();
Toast.makeText(this, "数据保存到text.txt文件了", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "未找到内存卡", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
记录表