Android知识点总结--(三)--文件读写工具类

1. 创建文件:

    /**
     * 创建一个文件
     * @param FileName 文件名
     * @return
     */
    public static File createFile(String FileName) {
        String path = Environment.getExternalStorageDirectory().toString() + "/1nmpaapp";
        File file = new File(path);
        /**
         *如果文件夹不存在就创建
         */
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(path, FileName);
    }

2. 写入数据:(FileOutputStream,BufferedOutputStream)

public static void getFile(byte[] bfile, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            file = createFileEm("3",fileName,"");
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

3. 删除手机中的图片:

public static void deleteFile(Context mContext,String path) {
        Log.e(TAG,"deleteFile  path="+path);
        File file = new File(path);
        //删除系统缩略图
        mContext.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[]{path});
        //删除手机中图片
        file.delete();
    }

有的机型,这样删除后会有残留,需要更新媒体库:

public static void updateMediaStore(final  Context context, final String path) {
    //版本号的判断  4.4为分水岭,发送广播更新媒体库
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        MediaScannerConnection.scanFile(context, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                mediaScanIntent.setData(uri);
                context.sendBroadcast(mediaScanIntent);
            }
        });
    } else {
        File file = new File(path);
        String relationDir = file.getParent();
        File file1 = new File(relationDir);
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
    }
}

有的地方更新媒体库时,只有:

Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(new File(imgPath)));
sendBroadcast(intent);

4.  在apk中打开某个word文件:

实际应用:从app中下载word文档后自动打开查看文档内容:

    public static void openDoc(Context mContext,File file) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
            data = FileProvider.getUriForFile(mContext, "com.nmpa.nmpaapp.file.provider", file);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(file);
        }
        intent.addFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
        //如果不加判断,直接用Uri.fromFile的形式传参,会报错
        intent.setDataAndType(data, "application/msword");
        mContext.startActivity(intent);
    }

5. 获取拍照相片存储文件

/**
     * 获取拍照相片存储文件
     * @param context
     * @return
     */
    public static File createFile(Context context){
        File file;
        String savePath = Environment.getExternalStorageDirectory().toString() + "/photo/";
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            String timeStamp = String.valueOf(new Date().getTime());
            file = new File(savePath + timeStamp+".jpg");
        }else{
            File cacheDir = context.getCacheDir();
            String timeStamp = String.valueOf(new Date().getTime());
            file = new File(cacheDir, timeStamp+".jpg");
        }
        return file;
    }

6. 获取本地图片的路径:

实际应用:从系统文件中选择一个文件,并获取这个文件的实际路径:

public static String handleImageOnKitKat(Context context, Intent data) {
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(context, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                String type = docId.split(":")[0];
                Uri contentUri = null;
                if (type.equalsIgnoreCase("image")) {
                    contentUri =  MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if (type.equalsIgnoreCase("audio")) {
                    contentUri =  MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else if (type.equalsIgnoreCase("video")) {
                    contentUri =  MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                }
                return getImagePath(context, contentUri, selection);
            } else if ("com.android.providers.media.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
                return getImagePath(context, contentUri, null);
            } else if ("content".equals(uri.getAuthority())) {
                return getImagePath(context, uri, null);
            } else if ("file".equals(uri.getAuthority())) {
                return uri.getPath();
            }
        }
        return "";
    }



    private static String getImagePath(Context context, Uri uri, String selection) {
        String path = null;
        Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

7. 保存bitmap到本地(FileOutputStream)

public static String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath = Environment.getExternalStorageDirectory().toString() + "/1nmpaapp/";
        File filePic;
        try {

            filePic = new File(savePath + System.currentTimeMillis() + ".jpg");
            Log.d("LUO", "图片地址====" + filePic);
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            //不压缩,保存本地
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return filePic.getAbsolutePath();
    }

8. 启动相机程序

    public static void takePhoto(Activity mContext, int requestCode) {
        // 启动相机程序
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mContext.startActivityForResult(intent, requestCode);
    }

9. 从拍照返回的数据中保存图片并返回图片路径(FileOutputStream)

public static String getCameraData(Intent data) {
        String path = null;
        Bitmap photo = null;
        if (data.getData() != null || data.getExtras() != null) { // 防止没有返回结果
            Uri uri = data.getData();
            if (uri != null) {
                photo = BitmapFactory.decodeFile(uri.getPath()); // 拿到图片
            }

            if (photo == null) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    photo = (Bitmap) bundle.get("data");
                    String saveDir = Environment.getExternalStorageDirectory().toString() + "/nmpaapp/";
                    String filename = System.currentTimeMillis() + ".jpg";
                    File file = new File(saveDir, filename);
                    FileOutputStream fileOutputStream = null;
                    // 打开文件输出流
                    try {
                        fileOutputStream = new FileOutputStream(file);
                        // 生成图片文件
                        photo.compress(Bitmap.CompressFormat.JPEG,
                                100, fileOutputStream);
                        path = file.getPath();
                        Log.e("FileLoadUtils", "str=" + path);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        if (fileOutputStream != null) {
                            try {
                                fileOutputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        return path;
    }

10. 获取视频文件的缩略图

    public static String getThumnailPath(String fromUser,String videoPath) {
        String fileName = "thvideo" + System.currentTimeMillis();
        File file = createFileEm("5",fileName,fromUser);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
            ThumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

11. 压缩图片(ByteArrayOutputStream,ByteArrayInputStream)

    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;
        int length = baos.toByteArray().length / 1024;
        Log.e(TAG,"length="+length);
        //循环判断如果压缩后图片是否大于1M,大于继续压缩
        while (baos.toByteArray().length / 1024>1024) {
            //重置baos即清空baos
            baos.reset();
            //这里压缩options%,把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            //每次都减少10
            options -= 10;
        }

        //把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        //把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

12,获取指定文件大小

    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

13. 获取指定文件夹的大小

private static long getFileSizes(File f) throws Exception
{
    long size = 0;
    File flist[] = f.listFiles();
    for (int i = 0; i < flist.length; i++){
        if (flist[i].isDirectory()){
            size = size + getFileSizes(flist[i]);
        }
        else{
            size =size + getFileSize(flist[i]);
        }
    }
    return size;
}

14. 转换文件大小

private static String FormetFileSize(long fileS)
{
    DecimalFormat df = new DecimalFormat("#.00");
    String fileSizeString = "";
    String wrongSize="0B";
    if(fileS==0){
        return wrongSize;
    }
    if (fileS < 1024){
        fileSizeString = df.format((double) fileS) + "B";
     } else if (fileS < 1048576){
        fileSizeString = df.format((double) fileS / 1024) + "KB";
    } else if (fileS < 1073741824){
        fileSizeString = df.format((double) fileS / 1048576) + "MB";
    } else {
        fileSizeString = df.format((double) fileS / 1073741824) + "GB";
    }
    return fileSizeString;
}

15. 转换文件大小,指定转换的类型

private static double FormetFileSize(long fileS,int sizeType)
{
    DecimalFormat df = new DecimalFormat("#.00");
    double fileSizeLong = 0;
    switch (sizeType) {
        case SIZETYPE_B:
            fileSizeLong=Double.valueOf(df.format((double) fileS));
            break;
        case SIZETYPE_KB:
            fileSizeLong=Double.valueOf(df.format((double) fileS / 1024));
            break;
        case SIZETYPE_MB:
            fileSizeLong=Double.valueOf(df.format((double) fileS / 1048576));
            break;
        case SIZETYPE_GB:
            fileSizeLong=Double.valueOf(df.format((double) fileS / 1073741824));
            break;
        default:
            break;
    }
    return fileSizeLong;
}

16. 自动计算指定文件或指定文件夹的大小

public static String getAutoFileOrFilesSize(String filePath) {
    File file = new File(filePath);
    long blockSize = 0;
    try {
        if (file.isDirectory()) {
            blockSize = getFileSizes(file);
        } else {
            blockSize = getFileSize(file);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("获取文件大小","获取失败!");
    }
    return FormetFileSize(blockSize);
}

17. 复制单个文件

public static boolean copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                fs.close();
                inStream.close();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

18. 从文件读取数据(FileReader,BufferedReader)

public static String readFromFile(String path) {
        try {
            File file = new File(path);
            if ( !file.exists() ) {
                return null;
            }

            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String buffer = "";
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer += line + "\n";
            }

            br.close();
            fr.close();
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

19. 写入数据;(FileWriter)

    public static void saveToFile(String path, String text) {
        try {
            File file = new File(path);

            if ( !file.exists() ) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file);
            fw.write(text);

            fw.flush();
            fw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值