Android 文件的读取与写入
一:Android中文件读取更具文件位置可分为三种:
第一种:从asset读取数据:
- //方法:从asset中获取文件并读取数据
- public String getFromAsset(String fileName){
- String result="";
- try{
- InputStream in = getResources().getAssets().open(fileName); //从Assets中的文件获取输入流
- int length = in.available(); //获取文件的字节数
- byte [] buffer = new byte[length]; //创建byte数组
- in.read(buffer); //将文件中的数据读取到byte数组中
- result = EncodingUtils.getString(buffer, ENCODING); //将byte数组转换成指定格式的字符串
- }
- catch(IOException e){
- e.printStackTrace(); //捕获异常并打印
- }
- catch(Exception e){
- e.printStackTrace();
- }
- return result;
- }
- //方法:从resource中的raw文件夹中获取文件并读取数据
- public String getFromRaw(String fileName){
- String result = "";
- try{
- InputStream in = getResources().openRawResource(R.raw.test1); //从Resources中raw中的文件获取输入流
- int length = in.available(); //获取文件的字节数
- byte [] buffer = new byte[length]; //创建byte数组
- in.read(buffer); //将文件中的数据读取到byte数组中
- result = EncodingUtils.getString(buffer, ENCODING); //将byte数组转换成指定格式的字符串
- in.close(); //关闭输入流
- }
- catch(IOException e){
- e.printStackTrace(); //捕获异常并打印
- }
- catch(Exception e){
- e.printStackTrace();
- }
- return result;
- }
第三种:从系统文件或sd卡读取数据:
- //方法:打开指定文件,读取其数据,返回字符串对象
- public String readFileData(String fileName){
- String result="";
- try{
- FileInputStream fin = openFileInput(fileName);<span style="white-space:pre"> </span>//获得FileInputStream对象
- int length = fin.available();<span style="white-space:pre"> </span>//获取文件长度
- byte [] buffer = new byte[length]<span style="white-space:pre"> </span>;//创建byte数组用于读入数据
- fin.read(buffer);//将文件内容读入到byte数组中
- result = EncodingUtils.getString(buffer, ENCODING);<span style="white-space:pre"> </span>//将byte数组转换成指定格式的字符串
- fin.close(); //关闭文件输入流
- }
- catch(Exception e){
- e.printStackTrace();<span style="white-space:pre"> </span>//捕获异常并打印
- }
- return result;<span style="white-space:pre"> </span>//返回读到的数据字符串
- }
- }
两者方法通用:
- void writeData(String filename,String msg){
- try {
- FileOutputStream fos=this.openFileOutput(filename, MODE_PRIVATE);
- byte[] buf=msg.getBytes();
- fos.write(buf);
- fos.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }