当前位置: 代码迷 >> Android >> Android从assets跟raw中读取txt文件
  详细解决方案

Android从assets跟raw中读取txt文件

热度:15   发布时间:2016-04-28 02:30:27.0
Android从assets和raw中读取txt文件

方法一、将要读取的txt文件拷贝到Android工程目录下的assets文件夹下

方法二、在res文件夹下新建raw文件夹,将txt拷贝到该目录下


本方法是从assets中读取

	/**	 * 从assets中读取txt	 */	private void readFromAssets() {		try {			InputStream is = getAssets().open("qq.txt");			String text = readTextFromSDcard(is);			textView.setText(text);		} catch (Exception e) {			// TODO Auto-generated catch block			e.printStackTrace();		}	}


本方法是从raw中读取

	/**	 * 从raw中读取txt	 */	private void readFromRaw() {		try {			InputStream is = getResources().openRawResource(R.raw.qq);			String text = readTextFromSDcard(is);			textView.setText(text);		} catch (Exception e) {			// TODO Auto-generated catch block			e.printStackTrace();		}	}

本方法是解析输入流,返回txt中的字符串

	/**	 * 按行读取txt	 * 	 * @param is	 * @return	 * @throws Exception	 */	private String readTextFromSDcard(InputStream is) throws Exception {		InputStreamReader reader = new InputStreamReader(is);		BufferedReader bufferedReader = new BufferedReader(reader);		StringBuffer buffer = new StringBuffer("");		String str;		while ((str = bufferedReader.readLine()) != null) {			buffer.append(str);			buffer.append("\n");		}		return buffer.toString();	}



  相关解决方案