1.说明:
>应用运行需要的一些较大的数据或图片可以用文件保存到手机内部
>文件类型: 任意
>数据保存的路径:/data/data/projectPackage/files/
>可以设置数据只能是当前应用读取,而别的应用不可以
>应用卸载时会删除此数据
2.相关API
1)读取文件
> FileInputStream fis = openFileInput("logo.png");
2)保存文件
> FileOutputStream fos = openFileOutput("logo.png", Context.MODE_PRIVATE);
3)得到files文件夹对象
> File filesDir = getFilesDir();
4)操作assets下的文件
>得到AssetManager : context.getAssets();
>读取文件 : InputStream open(filename);
5)加载图片文件
> Bitmap BitmapFactory.decodeFile(String pathName)
3.相关代码
(其中为了方便用throw,应该用try-catch处理)
public class IfActivity extends Activity {
private ImageView iv_if;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_if);
iv_if = (ImageView) findViewById(R.id.iv_if);
}
public void save(View v) throws IOException {
// 1.得到InputStream--> 读取assets下的logo.png
// 得到AssetManager
AssetManager manager = getAssets();
// 读取文件
InputStream is = manager.open("logo.png");
// 2.得到OutputStream--> /data/data/packageName/files/logo.png
FileOutputStream fos = openFileOutput("logo.png", Context.MODE_PRIVATE);
// 3.边读边写
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
// 关闭流
fos.close();
is.close();
// 4.提示
Toast.makeText(this, "保存完成", 0).show();
}
public void read(View v) {
// 1.得到图片文件的路径
// /data/data/packageName/files
String filesPath = getFilesDir().getAbsolutePath();
String imagePath = filesPath + "/logo.png";
// 2.读取加载图片文件得到bitmap对象
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
// 3. 将其设置到imageView中显示
iv_if.setImageBitmap(bitmap);
}
}