在这一讲我给大家讲一下关于android对于文件的处理(创建和编辑),这里所说的的文件处理,其中的文件不止包括文本文件也包括视频文件、音乐文件等…
- 文件的创建
File sdcard = Environment.getExternalStorageDirectory();
File myfile = new File(sdcard,"This is my file.txt");
myfile.createNewFile();
这样的话就把文件This is This is my file.txt创建好了,接下来就是文件的编辑(读取数据和写入数据)
文件的编辑
文件的读取
findViewById(R.id.wreadBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LogUtil.log("start Read");
File sdcard = Environment.getExternalStorageDirectory();
File myfile = new File(sdcard,"This is my file.txt");
if(myfile.exists()){
try {
FileInputStream fis = new FileInputStream(myfile);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char[] input = new char[fis.available()] ;
isr.read(input);
String inString = new String(input);
show.setText(inString);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
文件的写入
findViewById(R.id.wwriteBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File sdcard = Environment.getExternalStorageDirectory();
File myfile = new File(sdcard,"This is my file.txt");
if(!sdcard.exists()){
Toast.makeText(getApplicationContext(),"当前系统能够不具备SD卡目录",Toast.LENGTH_SHORT).show();
return ;
}
try {
myfile.createNewFile();
Toast.makeText(getApplicationContext(),"文件已经创建完成"+sdcard.toString(),Toast.LENGTH_LONG).show();
FileOutputStream fos = new FileOutputStream(myfile);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(et.getText().toString());
osw.flush();
osw.close();
fos.close();
Toast.makeText(getApplicationContext(),"文件已经写入完成",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
});