Android assets读写+SD卡读写

1.读取assets文本内容

方法1


    public String getContentFromAssets(String fileName) {
        //String path = "file:///android_asset/"+fileName;
        StringBuilder builder=new StringBuilder();
        try {
            InputStream is = getResources().getAssets().open(fileName);
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine())!=null){
                builder.append(line);
            }
            is.close();
        } catch (IOException e) {
            Log.v(TAG,"文件不存在");
        }
        return builder.toString();
    }

方法2

   //读取文件到byte[]
    public static byte[] getFileBytes(Context context, String file) {
        InputStream is = null;
        try {
            is = context.getResources().getAssets().open(file);
            int length = is.available();
            byte[] buffer = new byte[length];
            is.read(buffer);
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

2.读取assets图片

public Bitmap getImageFromAssetsFile(String fileName) {
        Bitmap image = null;
        try {
            InputStream is = getResources().getAssets().open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

3.将assets文件写入SD卡

3.1图片读写
assets下的图片存入SD,再根据SD路径获取图片

    //读取文本
    public Bitmap getImageFromSD(String fileName) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            MyToast.shortToast("SD卡不存在");
            return null;
        }
        //SD路径
        String path="";
        try {
            File sdCardDir = getExternalFilesDir(null);
            // /storage/emulated/0/Android/data/com.pfj.filedemo/files/Android_icon.png
            path = sdCardDir.getCanonicalPath() + "/"+fileName;
            //从assets读取图片流
            File file = new File(path);
            if (!file.exists()){
                Bitmap image = getImageFromAssetsFile(fileName);
                FileOutputStream out = new FileOutputStream(path);
                //这个方法非常赞(将图片压缩到path下)
                image.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//       路径: /storage/emulated/0//com.pfj.filedemo/files/Android_icon.png
        Log.e(TAG, path);
        Bitmap bm = BitmapFactory.decodeFile(path);
        return bm;
    }

将图片直接存入SD卡

	public boolean storeImageToSD(Bitmap bitmap, String imageName) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                File sdCardDir = getExternalFilesDir(null);
                //storage/emulated/0/Android/data/com.pfj.filedemo/files/imageName
                String path = sdCardDir.getCanonicalPath() + "/" + imageName;//创建SD路径
                FileOutputStream fos = new FileOutputStream(path);
                //压缩到内存
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

3.2文本读写
写入sd卡1

    public void writeContent2SD(Context context,String finame, String content) {
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File sdCardDir = context.getExternalFilesDir(null);
                File targetFile = new File(sdCardDir.getCanonicalPath() + "/"+finame);
                // /storage/emulated/0/Android/data/com.pfj.filedemo/files/FileName
                Log.v(TAG, targetFile.getAbsolutePath());
                //以指定文件创建RandomAccessFile对象
                RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");
                //记住,输入的时候位置是要用到指针的
                raf.seek(targetFile.length());
                //输出文件内容
                raf.write(content.getBytes());
                //关闭RandomAccessFile
                raf.close();
            } else {
                Toast.makeText(context, "请检查SD卡", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

写入sd卡2

  //bytes[]写入sdcard
  public void writebyte2sd(byte[] result){ 
	  String path = Environment.getExternalStorageDirectory().getPath();
	  FileOutputStream fileOutputStream = new FileOutputStream(path+"/1.yuv");
	  fileOutputStream.write(result);
	  fileOutputStream.flush();
	  fileOutputStream.close();
	  //InputStream is = context.getResources().getAssets().open(file);
	  //File outFile = new File("sdcard/", "aa.yuv");
      //FileOutputStream out = new FileOutputStream(outFile);
      //byte[] buffer = new byte[1024];
      //int read;
      //while ((read = is.read(buffer)) != -1) {
      //    out.write(buffer, 0, read);
      //}
      //out.close();
      //is.close();
  }

从sd卡读取

    public String readContentFromSD(Context context,String filename) {
        StringBuilder sb = new StringBuilder();
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File sdCardDir = context.getExternalFilesDir(null);
                //指定路径: /storage/emulated/0/Android/data/com.pfj.filedemo/files/文件名
                String path = sdCardDir.getCanonicalPath() + "/"+filename;
                File file = new File(path);
                //文件是否存在
                if (!file.exists()){
                    //从asset获取数据
                    String content = getContentFromAssets(filename);
                    //内容写入SD卡
                    writeContent2SD(context,filename,content);
                }
                InputStream fis = new FileInputStream(path);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                String line;
                //循环读取文件内容
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            } else {
                Toast.makeText(context, "请检查SD卡", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

从asserts读取数据,写入SD卡,再从SD卡读取

public String getContentFromSD(String fileName) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            MyToast.shortToast("SD卡不存在");
            return null;
        }
        File sdCardDir = getExternalFilesDir(null);
        String path="";
        try {
            path = sdCardDir.getCanonicalPath() + "/"+fileName;
            InputStream is = getResources().getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            BufferedWriter bw = new BufferedWriter(new FileWriter(path));
            String line = "";
            while ((line = reader.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
            bw.flush();
            bw.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.e(TAG, path);
        String s  = readContentFromSD(this,fileName);
        return s;
    }

保存Bitmap到手机

/**
     * 
     * 
     * 路径:/storage/emulated/0/filename
     * File file = new File(Environment.getExternalStorageDirectory(), filename);
     * 路径:/storage/emulated/0/Android/data/包名/files/filename
     * File file = new File(getExternalFilesDir(null), filename);
     * 路径:/data/data/包名/files/filename(查看需要root权限)
     * File file = new File(this.getFilesDir(), filename);
     */
    private boolean saveBitmap2SD(Bitmap bitmap, String filename) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "请检查SD卡", Toast.LENGTH_SHORT).show();
            return false;
        }
        try {
            File path = Environment.getExternalStorageDirectory();
            File file = new File(path, filename);
            if (!file.exists()) {
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值