Android文件读写实例代码
Android文件读写实例代码
本文主要是基于Android的文件创建和读写代码的例子,作为本人的代码资源记录下来,方便以后开发直接利用。现以在sdcard/sample目录创建名称为sample的txt文件的读写操作为例,说明代码实现过程。
1.Manifest文件中权限的声明
为了能对sdcard进行读写操作,即可创建文件或目录,需要在AndroidManifest.xml中添加权限的声明:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
final static String FOLDER = "/sample/";final static String FILENAME = "sample"; final static String SUFFIX = ".txt"; // suffix could be replaced on demand
private void writeFile(StringBuilder sb) { String foldername = Environment.getExternalStorageDirectory().getPath() + FOLDER; File folder = new File(foldername); if (folder != null && !folder.exists()) { if (!folder.mkdir() && !folder.isDirectory()) { Log.d(TAG, "Error: make dir failed!"); return; } } String stringToWrite = sb.toString(); String targetPath = foldername + FILENAME + SUFFIX; File targetFile = new File(targetPath); if (targetFile != null) { if (targetFile.exists()) { targetFile.delete(); } OutputStreamWriter osw; try{ osw = new OutputStreamWriter( new FileOutputStream(targetFile),"utf-8"); try { osw.write(stringToWrite); osw.flush(); osw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }}
private String readFile(String filepath) { String path = filepath; if (null == path) { Log.d(TAG, "Error: Invalid file name!"); return null; } String filecontent = null; File f = new File(path); if (f != null && f.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(f); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); Log.d(TAG, "Error: Input File not find!"); return null; } CharBuffer cb; try { cb = CharBuffer.allocate(fis.available()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); Log.d(TAG, "Error: CharBuffer initial failed!"); return null; } InputStreamReader isr; try { isr = new InputStreamReader(fis, "utf-8"); try { if (cb != null) { isr.read(cb); } filecontent = new String(cb.array()); isr.close(); } catch (IOException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Log.d(TAG, "readFile filecontent = " + filecontent); return filecontent;}