数据存储之文件存储

//1.文件的路径
        
//建立文件
File file = new File("/mnt/sdcard/test");
	if (!file.exists()) {
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		   }
		}else {
			Toast.makeText(MainActivity.this, "文件已存在", 1000);
		}

//删除文件
file.delete();

//得到内部文件路径
File file = this.getFilesDir();

//得到内部缓存路径
File file = this.getCacheDir();

//自定义权限路径 /data/data/<包名>/app_imooc
File file = this.getDir("imooc", MODE_PRIVATE);

//得到外部文件路径
File file = this.getExternalFilesDir(type);

//得到外部缓存路径
File file = this.getExternalCacheDir();


==================

//2.文件的读写
public class MainActivity extends Activity {
	EditText edt;
	Button but;
	TextView contentvalue;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edt = (EditText) findViewById(R.id.editText1);
		but = (Button) findViewById(R.id.write);
		contentvalue = (TextView) findViewById(R.id.contentvalue);
		but.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				WriteFiles(edt.getText().toString());
				contentvalue.setText(readFiles());
				
			}
		});
	}
	//文件写入
	public void WriteFiles(String content){
		 try {
			FileOutputStream fos = openFileOutput("a.txt", MODE_WORLD_READABLE+MODE_WORLD_WRITEABLE);
			 fos.write(content.getBytes());
			 fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
	}
	//文件写出
	public String readFiles(){
		String content = null;
		 try {
			FileInputStream fis= openFileInput("a.txt");
			 ByteArrayOutputStream baos =  new ByteArrayOutputStream();
			byte [] buffer =  new byte[1024];
			int len = 0;
           //每次从fis中读取一个字节buffer,直到把fis读完
			while ((len=fis.read(buffer))!=-1) {
				baos.write(buffer, 0, len);
			}
			content = baos.toString();
			fis.close();
			baos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return content;
	}
}

相关文章
相关标签/搜索