在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; }
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,下写到这里,待续