android中文件操作
android開發中涉及到的文件操作主要是往sd卡中或是內在中讀取文件數據,大概的操作如下:
public class FileOperator {
private Context context; //上下文 public FileOperator(Context c) {
this.context = c;
}//首先是個公用的方法: private String dealStream(InputStream is) throws IOException {
int buffersize = is.available();// 取得輸入流的字節長度
byte buffer[] = new byte[buffersize];
is.read(buffer);// 數據讀入數組
is.close();// 讀取完畢關閉流。
String result = EncodingUtils.getString(buffer, "UTF-8");// 防止亂碼
return result;
}// 讀取sd中的存在的文件 public String readSDCardFile(String path) throws IOException { File file = new File(path); FileInputStream fis = new FileInputStream(file); String resStr = dealStream(fis); return resStr ; } // res目錄下新建raw資源文件夾,只能讀不能寫入 public String readRawFile(int fileId) throws IOException { // 取得輸入流 InputStream is = context.getResources().openRawResource(fileId); String resultStr = dealStream(is);// 返回一個字符串 return resultStr; } // 在assets下的文件,只能讀取不能寫入 public String readAssetsFile(String filename) throws IOException { // 取得輸入流 InputStream is = context.getResources().getAssets().open(filename); String resStr = dealStream(is);// 返回一個字符串 return resStr; } // 往sd卡中寫入文件 public void writeToSDCard(String path, byte[] buffer) throws IOException { File file = new File(path); FileOutputStream fos = new FileOutputStream(file); fos.write(buffer);// 寫入buffer數組。如果想寫入一些簡單的字符,可以將String.getBytes()再寫入文件; fos.close(); } // 將文件寫入應用的data/data的files目錄下 public void writeToDateFile(String fileName, byte[] buffer) throws Exception { byte[] buf = fileName.getBytes("iso8859-1"); fileName = new String(buf, "utf-8"); FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_APPEND);// 打開模式,有幾種,此處表示添加在文件后面 fos.write(buffer); fos.close(); } // 讀取應用的data/data的files目錄下文件數據 public String readDateFile(String fileName) throws Exception { FileInputStream fis = context.openFileInput(fileName); String resultStr = dealStream(fis);// 返回一個字符串 return resultStr; }
} </pre>
最后我們不要忘記在清單文件AndroidManfiest.xml中加上sd卡操作權限:<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> //在SDCard中創建與刪除文件權限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> //往SDCard寫入數據權限
本文由用戶 f663x 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!