文件存储工具类

最近写的一个文件存储的工具类

包括文件存入与读取还有判断SD卡是否可用

public class FileTools {

    /**写入文件操作*/
    public static void writeTxtFile(String FileName ,String Message){
        if(getExternalStorageState()){
            File file = new File("/sdcard/"+FileName);
            if(file.exists()){
                file.delete();
            }
            FileOutputStream out;
            try {
                out = new FileOutputStream(file);
                out.write(Message.getBytes());
                out.close();

            }catch (FileNotFoundException e){
                e.printStackTrace();
                LogUtil.e("error","FileNotFoundException!!");
            }catch (IOException e){
                e.printStackTrace();
                LogUtil.e("error","IOException!!");
            }
        }
    }

    /**读取文件操作*/
    public static  String readTxtFile(String FileName){
        FileInputStream fis = null;
        if(getExternalStorageState()){
            File file = new File("/sdcard/"+FileName);
            if(file.exists()){
                try{
                    fis = new FileInputStream(file);
                    int len = 0;
                    StringBuilder builder = new StringBuilder();
                    byte[] buffer = new byte[1024];

                    while ((len =fis.read(buffer))!=-1){
                        builder.append(new String(buffer,0,len));
//                        builder.append(buffer); //这里如果这样写会是乱码,因为是二进制的buffer 需要String构造一下才行
                    }
                    return builder.toString();
                }catch (FileNotFoundException e){
                    e.printStackTrace();
                    LogUtil.e("error","FileNotFoundException!!");
                }catch (IOException e){
                    e.printStackTrace();
                    LogUtil.e("error","IOException!!");
                }
            }
        }
        return null;
    }
/**从sd卡中读取图片*/
public static Bitmap loadBitmapFromSdcard(String fileName){
    String path = fileName;
    if(getExternalStorageState()){
        File file = new File(path);
        if(file.exists()){
            BitmapFactory.Options options=new BitmapFactory.Options();
            options.inSampleSize = 2;
            Bitmap bmp = BitmapFactory.decodeFile(path,options);
            if(bmp == null){
                file.delete();
            }else{
                return bmp;
            }
        }
    }
    return null;
}
/** * 判断SD卡是否可用 * */ private static boolean getExternalStorageState(){ String state = Environment.getExternalStorageState(); return state.equals(Environment.MEDIA_MOUNTED);
 } 
}

  

原文地址:https://www.cnblogs.com/fengfenghuifei/p/6221975.html