一. 概述 此例子将文本文件存入data/data/files中,只有本程序能够读取。 二. 实现 1. 保存文件 /**
* Save content to a file * @param fileName the name of the file * @param fileContent the content of the file * @throws IOException */ public void save(String fileName, String fileContent) throws IOException { FileOutputStream out = context.openFileOutput(fileName, Context.MODE_APPEND); out.write(fileContent.getBytes()); out.flush(); out.close(); } 2. 读取文件 /**
* read the content in data/data/com.like.app/files * @param fileName the name of the file * @param fileContent the content of the file * @return return the content of the file * @throws IOException */ public String read(String fileName, String fileContent) throws IOException { FileInputStream inputStream = context.openFileInput(fileName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } byte[] data = outputStream.toByteArray(); outputStream.close(); inputStream.close(); return new String(data); } 3. 保存文件至SD卡 (1) 在操作SD卡之前,需要加入权限 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> (2) 方法实现 /**
* save file to sdcard * @param fileName the name of the file * @param fileContent the content of the file * @throws IOException */ public void saveToSdcard(String fileName, String fileContent) throws IOException { //getExtrnalStorageDirectory() 获取sdcard路径 File file = new File(Environment.getExternalStorageDirectory(), fileName); FileOutputStream outputStream = new FileOutputStream(file); outputStream.write(fileContent.getBytes());
outputStream.close(); } 4. 从SD卡读取文件 /**
* read content from sdcard * @param fileName the name of the file * @param fileContent the content of the file * @return return the content of the file * @throws IOException */ public String readFromSdcard(String fileName, String fileContent) throws IOException { FileInputStream inputStream =
new FileInputStream( new File(Environment.getExternalStorageDirectory(), fileName)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0;
while((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } byte[] data = outputStream.toByteArray(); outputStream.close(); inputStream.close(); return new String(data); }
|
|
来自: 黎可图书馆 > 《Android学习》