work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Android 文件操作

Posted on 2013-03-28 09:55  work hard work smart  阅读(221)  评论(0编辑  收藏  举报

Android 文件操作操作时,要赋予相应的权限:

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 下面是向文件写文本的代码:

         private final static String PATH = "/sdcard/lin";
	private final static String FILENAME = "/test.txt";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		writeFile();
	}

	private void writeFile() {
		//判断设备是否存在sdcard
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			try {
				Log.d("File Operation", "start!");
				File path = new File(PATH);
				File file = new File(PATH+FILENAME);
				//如果不存在此路径,则创建此路径
				if (!path.exists()) {
					path.mkdir();
				}
				//如果不存在此文件,则创建此文件
				if (!file.exists()) {
					file.createNewFile();
				}
				//将"text message!"信息写入相应的文件
				OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file));
				osw.write("text message!");
				osw.close();
				Log.d("File Operation", "success!");
			} catch (Exception e) {
				Log.d("File Operation", "file create error");
			}
			
		}
		
	}