Android 文件存取总结

来源:互联网 发布:mac 退出less 编辑:程序博客网 时间:2024/06/10 22:45

总结内容如下:

NO1:Android文件存取

NO2:java File 类

NO3:代码实现

NO1:Android 文件目录分为私有目录和公有目录

1.Android 私有目录(要用Android自己的方法来存取)

卸载时,文件会被清除
目录结构:
a./data/data/package name/cache
b./data/data/package name/file

文件私有目录的读 openFileInput(String name)

FileInputStream in = openFileInput(“xixi”);

文件私有目录的写 openFileOutput(String name, int mode)

其中第二个参数是写出模式,模式有四种:

_1. Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容。
_2. Context.MODE_APPEND:此模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
_3. MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;
_4. MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
假如希望文件被其他应用读和写,可以这样写:
openFileOutput(“zyc.txt”, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

2.SD卡 公共目录(用java.io 来存取)

卸载时,文件不会被清除
目录结构:
mnt/sdcard/

NO2:Java File类构造方法

  1. File(File dir, String name) 参数1:文件目录,参数2:文件名
    File fileCache = new File(getCacheDir(), “xi”);
  2. File(String path) 参数:文件的路径
    File path = new File(A.SDPath.getAbsolutePath());
    3.File(String dirPath, String name) 参数1:文件目录路径,参数2:文件名
    File file2 = new File(“getFilesDir().getAbsolutePath()”, “xi2”);
  3. File file3 = new File(uri); 参数uri:文件的uri表示

NO3:代码实现

1、存文本文件到私有目录

代码如下:

存数据:

        try {            //拿取assets数据            open = getResources().getAssets().open(fileName);            //限制为本应用使用的资源            //写到/data/data/<package name>/files            fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);            int len;            //每次操作1M            byte[] buffer = new byte[1024];            //循环读写数据,直到文件处理完            while ((len = open.read(buffer)) != -1) {                //每次读1M数据                open.read(buffer);                //文件长度不确定,及时将buffer中的数据写出去                fileOutputStream.write(buffer, 0, len);            }            //防止数据丢失,刷新            fileOutputStream.flush();            Toast.makeText(MainActivity.this, "文件" + fileName + "存取成功!", Toast.LENGTH_SHORT).show();        } catch (IOException e) {            Log.e(TAG, "读取assets文件IO异常" + e);        } finally {            //防止leak,关闭流            if (null != open) {                try {                    open.close();                } catch (IOException e) {                    Log.e(TAG, "关闭输入流失败" + e);                }            }            if (null != fileOutputStream) {                try {                    fileOutputStream.close();                } catch (IOException e) {                    Log.e(TAG, "关闭输出流失败" + e);                }            }        }

读数据:

        try {            FileInputStream fis = openFileInput(fileName);            int available = fis.available();            byte[] buffer = new byte[available];            fis.read(buffer);            Toast.makeText(MainActivity.this, new String(buffer).trim().toString(), Toast.LENGTH_SHORT).show();            System.out.println(new String(buffer).trim().toString());        } catch (FileNotFoundException e) {            Log.e(TAG, "读取文件失败" + e);        } catch (IOException e) {            Log.e(TAG, "读取文件IO异常" + e);        }

注释很清晰,就不做说明了。

2、存图片到私有目录

存储图片到私有目录:

        try {            //拿取assets数据            open = getResources().getAssets().open(fileName);            //限制为本应用使用的资源            //写到/data/data/<package name>/files            fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);            Bitmap.CompressFormat localCompressFormat = Bitmap.CompressFormat.JPEG;            Bitmap bitmap = BitmapFactory.decodeStream(open);            bitmap.compress(localCompressFormat, 100, fileOutputStream);            Toast.makeText(MainActivity.this, "文件" + fileName + "存取成功!", Toast.LENGTH_SHORT).show();        } catch (IOException e) {            Log.e(TAG, "读取assets文件IO异常" + e);        } finally {            //防止leak,关闭流            if (null != open) {                try {                    open.close();                } catch (IOException e) {                    Log.e(TAG, "关闭输入流失败" + e);                }            }            if (null != fileOutputStream) {                try {                    fileOutputStream.close();                } catch (IOException e) {                    Log.e(TAG, "关闭输出流失败" + e);                }            }        }

显示存储在私有目录的图片:

读图片:

        //显示图片        try {            fis = openFileInput(fileName);            int len = fis.available();            //将流转为byte            byte[] buffer = new byte[len];            fis.read(buffer);//            Toast.makeText(MainActivity.this,new String(buffer).trim(),Toast.LENGTH_SHORT).show();            showPic(buffer);        } catch (FileNotFoundException e) {            Log.e(TAG, "找不到" + fileName + e);        } catch (IOException e) {            Log.e(TAG, fileName + "IO异常" + e);        }finally {            if (null != fis){                try {                    fis.close();                } catch (IOException e) {                    Log.e(TAG,"fis关闭IO异常" + e);                }            }        }

显示图片showPic():

{        Log.i(TAG,"图片byte" + new String(b));        Dialog dialog = new Dialog(MainActivity.this, R.style.my_dialog);        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.show_pic, null);        dialog.setContentView(view);        ImageView iv = (ImageView) view.findViewById(R.id.iv_show);        Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);        if (null != bitmap) {            Toast.makeText(MainActivity.this, "图片成功了", Toast.LENGTH_LONG).show();            iv.setImageBitmap(bitmap);        } else {            Toast.makeText(MainActivity.this, "图片为空", Toast.LENGTH_LONG).show();        }        Window window = dialog.getWindow();        WindowManager.LayoutParams attributes = window.getAttributes();        attributes.height = (int) (A.getDisplayMetrics(MainActivity.this).heightPixels * 0.8);        attributes.width = (int) (A.getDisplayMetrics(MainActivity.this).widthPixels * 0.66);        window.setAttributes(attributes);        dialog.show();    }

3、存储文本文件到公有目录

存储文本文件到SD卡:

        try {            //拿取assets数据            open = getResources().getAssets().open(fileName);            //首先要判断sd卡,是否已经挂载            boolean b = ExistSDCard();            if (!b) {                Toast.makeText(this, "没有sd卡", Toast.LENGTH_SHORT).show();                return;            }            //目录是否存在            File dir = new File(A.textPath);            if (!dir.exists()) {                dir.mkdir();            }            //文件是否存在            path = A.textPath + "testFile.txt";            File file = new File(path);            if (!file.exists()) {                try {                    file.createNewFile();                } catch (Exception e) {                    e.printStackTrace();                }            }            fileOutputStream = new FileOutputStream(path);            int len;            //每次操作1M            byte[] buffer = new byte[1024];            //循环读写数据,直到文件处理完            while ((len = open.read(buffer)) != -1) {                //每次读1M数据                open.read(buffer);                //文件长度不确定,及时将buffer中的数据写出去                fileOutputStream.write(buffer, 0, len);            }            //防止数据丢失,刷新            fileOutputStream.flush();            Toast.makeText(MainActivity.this, "文件" + fileName + "存取成功!", Toast.LENGTH_SHORT).show();        } catch (IOException e) {            Log.e(TAG, "读取assets文件IO异常" + e);        } finally {            //防止leak,关闭流            if (null != open) {                try {                    open.close();                } catch (IOException e) {                    Log.e(TAG, "关闭输入流失败" + e);                }            }            if (null != fileOutputStream) {                try {                    fileOutputStream.close();                } catch (IOException e) {                    Log.e(TAG, "关闭输出流失败" + e);                }            }        }    }

existSDCard:

  private boolean existSDCard() {        if (android.os.Environment.getExternalStorageState().equals(                android.os.Environment.MEDIA_MOUNTED)) {            return true;        } else            return false;    }

读sd卡文本文件:

        try {            FileInputStream fis = new FileInputStream(path);            int ll = fis.available();            byte[] buffer = new byte[ll];            fis.read(buffer, 0, ll);            System.out.println(new String(buffer).toString());            Toast.makeText(this, new String(buffer).toString(), Toast.LENGTH_SHORT).show();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }

4、存储图片到公有目录

存储图片到sd:

 try {                //拿取assets数据                open = getResources().getAssets().open(fileName);                //判断sd卡                if(!existSDCard()){                    Toast.makeText(this,"没有SD卡",Toast.LENGTH_SHORT).show();                    return;                }                File dir = new File(A.picPath);                if(!dir.exists()){                    dir.mkdir();                }                path = A.picPath + "picTest.jpg";                File file = new File(path);                if(!file.exists()){                    file.createNewFile();                }                fileOutputStream = new FileOutputStream(path);                Bitmap.CompressFormat localCompressFormat = Bitmap.CompressFormat.JPEG;                Bitmap bitmap = BitmapFactory.decodeStream(open);                bitmap.compress(localCompressFormat, 100, fileOutputStream);                //防止数据丢失,刷新                fileOutputStream.flush();                Toast.makeText(MainActivity.this, "文件" + fileName + "存取成功!", Toast.LENGTH_SHORT).show();            } catch (IOException e) {                Log.e(TAG, "读取assets文件IO异常" + e);            } finally {                //防止leak,关闭流                if (null != open) {                    try {                        open.close();                    } catch (IOException e) {                        Log.e(TAG, "关闭输入流失败" + e);                    }                }                if (null != fileOutputStream) {                    try {                        fileOutputStream.close();                    } catch (IOException e) {                        Log.e(TAG, "关闭输出流失败" + e);                    }                }            }

从SD读取图片并显示:

  try {            FileInputStream fis = new FileInputStream(path);            int len = fis.available();            byte[] buffer = new byte[len];            fis.read(buffer,0,len);            showPic(buffer);        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }

OK 今天的总结就到这了,代码很简单,但是是很重要的Android 基础知识!

1 0
原创粉丝点击