日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Android入门:实现一个File存储的辅助类

發布時間:2025/7/14 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android入门:实现一个File存储的辅助类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

File文件存儲博客鏈接:http://blog.csdn.net/xiazdong/article/details/7687439

?

package com.xiazdong.file.util;import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream;import android.content.Context; import android.os.Environment;public class FileUtil {/*** 保存文本到內存* @param context* @param filename* @param content* @param mode* @throws Exception*/public static void saveTextInMemory(Context context,String filename,String content,int mode) throws Exception{try{FileOutputStream out = context.openFileOutput(filename, mode);out.write(content.getBytes("UTF-8"));out.close();}catch(Exception e){throw new Exception();}}/*** 保存文件到sdcard* @param filename* @param content* @throws Exception*/public static void saveTextInSdcard(String filename,String content) throws Exception{try{File f = new File(Environment.getExternalStorageDirectory(),filename);FileOutputStream out = new FileOutputStream(f);out.write(content.getBytes("UTF-8"));out.close();}catch(Exception e){throw new Exception();}}/*** 從內存讀取文件* @param filename* @return* @throws Exception*/public static String loadTextFromSdcard(String filename) throws Exception{try{File f = new File(Environment.getExternalStorageDirectory(),filename);FileInputStream in = new FileInputStream(f);byte[]data = read2byte(in);return new String(data,"UTF-8");}catch(Exception e){throw new Exception();}}/*** 從sdcard讀取文件 * @param context* @param filename* @return* @throws Exception*/public static String loadTextFromMemory(Context context,String filename) throws Exception{try{FileInputStream in = context.openFileInput(filename);byte[]data = read2byte(in);return new String(data,"UTF-8");}catch(Exception e){throw new Exception();}}private static byte[] read2byte(InputStream in) throws IOException {byte[] data;ByteArrayOutputStream bout = new ByteArrayOutputStream();byte[]buf = new byte[1024];int len = 0;while((len = in.read(buf))!=-1){bout.write(buf, 0, len);}data = bout.toByteArray();return data;} }

?

測試代碼:

FileUtil.saveTextInSdcard("1.txt","hello"); //將"hello"保存到/mnt/sdcard/1.txt中 String content = FileUtil.loadTextFromSdcard("1.txt"); //讀取/mnt/sdcard/1.txt內容 FileUtil.saveTextInMemory(MainActivity.this,"1.txt","hello", Context.MODE_PRIVATE); //將hello保存到/data/data/package/files/1.txt中 String content = FileUtil.loadTextFromMemory(MainActivity.this, "1.txt"); //讀取/data/data/package/files/1.txt內容


?

轉載于:https://www.cnblogs.com/xiazdong/archive/2012/07/09/3058320.html

總結

以上是生活随笔為你收集整理的Android入门:实现一个File存储的辅助类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。