Android中的文件的读取方法
16lz
2021-01-23
在Android中根据文件位置的不同,可分为四种文件读取方式,具体如下;
//方法:从resource中的raw文件夹中获取文件并读取数据,注意:只能读取不能写入数据
public String getFromRaw(int fileId) { InputStream in = null; String result = ""; ByteArrayOutputStream baos=null; try { // 获取Resources资源文件流 in = getResources().openRawResource(fileId); // 文件大小 int length = in.available(); // 创建byte数组 byte[] buf = new byte[length]; // 创建内存流加快效率 baos = new ByteArrayOutputStream(); int count = 0; while ((count = in.read(buf)) != -1) { baos.write(buf, 0, count); } result=new String(baos.toByteArray(), "UTF-8"); //result = EncodingUtils.getString(buf, "UTF-8"); } catch (IOException e) { Toast.makeText(this, "找不到文件", 2000).show(); } finally{ if(baos!=null) try { baos.close(); } catch (IOException e) { e.printStackTrace(); } if(in!=null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
//方法:从asset中获取文件并读取数据,只能读取不能写入数据
public String getFromAsset(String fileName){//fileName="read_asset.txt" InputStream in = null; String result = ""; ByteArrayOutputStream baos=null; try{ in = getAssets().open(fileName); int size = in.available(); byte[] buffer = new byte[size]; baos = new ByteArrayOutputStream(); while(in.read(buffer)!=-1){ baos.write(buffer); } // Convert the buffer into a string. // result = new String(baos.toByteArray(),"UTF-8"); result = EncodingUtils.getString(baos.toByteArray(), "UTF-8"); }catch(IOException e){ Toast.makeText(this, "找不到文件", 2000).show(); } finally{ if(baos!=null) try { baos.close(); } catch (IOException e) { e.printStackTrace(); } if(in!=null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
//方法:向指定系统文件中写入指定的数据
public void writeFileData(String fileName, String message) {FileOutputStream fos = null;try {fos = openFileOutput(fileName, Context.MODE_PRIVATE);byte[] bytes = message.getBytes();fos.write(bytes);fos.flush();} catch (IOException e) {Toast.makeText(this, "文件写入错误", 2000).show();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}
//方法:打开指定系统文件读取其数据,
public String readFileData(String fileName){ FileInputStream fis=null; String result=""; try{ fis = openFileInput(fileName); int size = fis.available(); byte [] buffer = new byte[size]; fis.read(buffer); result=new String(buffer,"UTF-8"); }catch(IOException e){ Toast.makeText(this, "文件没有找到", 2000).show(); }finally{ if(fis!=null){ try {fis.close();} catch (IOException e) {e.printStackTrace();} } } return result;//返回读到的数据字符串 }
ok,下写到这里,待续
更多相关文章
- Android studio cmd命令行操作数据库文件导出,导入
- Android设备开机后自动启动APP解决方法:(学习篇)
- Android 文字自动滚动(跑马灯)效果的两种实现方法[特别好使]
- android的文件存储
- Android Fragment 生命周期及回调方法
- 部分 CM11 系统 Android 平板执行植物大战僵尸 2 黑屏的解决的方
- Android 在Service开启对话框的方法
- Fiddler 跟踪 Android 数据包
- 理解 Android 本地数据存储 API