Android 读写文件的N种写法

长平狐 发布于 2013/01/06 11:17
阅读 60
收藏 0

Android 读写文件的N种写法(待续。。。)


读取raw文件

// 读取raw文件
	private void rawRead(){
		String ret = "";
		
		try {
			InputStream is = getResources().openRawResource(R.raw.my_raw);
			
			int len = is.available();
			byte []buffer = new byte[len];
			
			is.read(buffer);
			ret = EncodingUtils.getString(buffer, "utf-8");
			
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		tvTXT.setText(ret);
	}



读取assets文件

	// 读取assets文件
	private void assetsRead(){
		String fileName = "my_assets.txt";				// assets下文件
	//	String fileName = "test/my_assets_test.txt";	// assets下子目录文件
		String ret = "";
		
		try {
			InputStream is = getResources().getAssets().open(fileName);
			int len = is.available();
			byte []buffer = new byte[len];
			
			is.read(buffer);
			ret = EncodingUtils.getString(buffer, "utf-8");
					
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		tvTXT.setText(ret);
	}


读取sdcard文件

	// 读取sdcard文件
	private void sdcardRead(){
		String fileName = "/sdcard/my_sdcard.txt";				// assets下文件
	//	String fileName = "/sdcard/test/my_sdcard_test.txt";	// sdcard下子目录文件
		String ret = "";
		
		try {
			FileInputStream fis = new FileInputStream(fileName);
			
			int len = fis.available();
			byte []buffer = new byte[len];
			
			fis.read(buffer);
			ret = EncodingUtils.getString(buffer, "UTF-8");
			
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		tvTXT.setText(ret);
	}



运行效果:





原文链接:http://blog.csdn.net/sunboy_2050/article/details/7621795
加载中
返回顶部
顶部