一、File
File类的使用基本和java一致
关于安卓中的一些路径和文件创建
以下实力码代码
File file=new File(getFilesDir(),"test.txt");
Log.i("info","文件夹路径:"+getFilesDir().getAbsolutePath());
Log.i("info","文件路径:"+file.getAbsolutePath());
if(!file.exists()){
try {
Log.i("info","文件创建成功");
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else{
Log.i("info","文件创建失败");
Toast.makeText(MainActivity.this, "文件已存在", Toast.LENGTH_SHORT).show();
}
file.delete();//文件删除
File file = this.getFilesDir();//内部文件夹
Log.i("info",file.toString());
File file = this.getCacheDir();//内部临时文件夹
Log.i("info",file.toString());
File file = this.getExternalFilesDir("1.txt");//外部文件
Log.i("info",file.toString());
File file = this.getExternalCacheDir();//外部临时文件夹
Log.i("info",file.toString());
File file = this.getDir("geekband",MODE_PRIVATE);//自定义内部文件夹
Log.i("info",file.toString());
File的读取
继续实力码代码
此为一个可存储和读取EditText中文字显示在TextView的案例
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.main_et);
button = (Button) findViewById(R.id.main_button);
textView = (TextView) findViewById(R.id.main_tx);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
writeContent(editText.getText().toString());
textView.setText(readContent());
}
});
}
//写内容
public void writeContent(String content){
try {
FileOutputStream fos = openFileOutput("a.txt",MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//读内容
public String readContent(){
String content = null;
FileInputStream fis = null;
try {
fis = openFileInput("a.txt");
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
if((len=fis.read(buffer))!=-1){//读取一个buffer的长度 while if 都行? 他是一次读完的
Log.i("info","len:"+len);
baos.write(buffer,0,len);//写入buffer中数据的相同长度
}
content = baos.toString();
fis.close();
baos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}