万能存储工具类 SDCard存储  /data/data/存储 
assets存储 raw存储

粘贴过去就能够用了

<uses-permission android:name="android.permission.INTERNET" />

<!-- SDCard中创建与删除文件权限 -->

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <!-- 向SDCard写入数据权限 -->

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

package com.hexun.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL; import org.apache.http.util.EncodingUtils; import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log; /**
* 保存图片的类
*
*
*/
public class FileUtil { private final static String CACHE = "/image";
private final static String CHARSETNAME = "UTF-8"; /*************************** 从resource的raw中读取文件数据 *****************************************************/ /**
* raw中读取文件数据
*
* @param context
* @param fileName
* R.raw.test
* @return String 文件内容
*/
public static String readRaw(Context context, int fileName) {
try {
// 得到资源中的Raw数据流
InputStream in = context.getResources().openRawResource(fileName);
return readInToStr(in);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /*************************** 从resource的asset中读取文件数据 **************************************************/ /**
* asset中读取文件数据
*
* @param context
* @param fileName
* 文件名称
* @return String 文件内容
*/
public static String readAssets(Context context, String fileName) {
try {
if (isNullEmptyBlank(fileName)) {
return null;
}
// 得到资源中的asset数据流
InputStream in = context.getResources().getAssets().open(fileName);
return readInToStr(in);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /***************************** data/data/ *****************************************************************/ // MODE_PRIVATE 私有(仅仅能创建它的应用訪问) 反复写入时会文件覆盖
// MODE_APPEND 私有 反复写入时会在文件的末尾进行追加。而不是覆盖掉原来的文件
// MODE_WORLD_READABLE 公用 可读
// MODE_WORLD_WRITEABLE 公用 可读写
/**
* 写数据/data/data/
*
* @param context
* @param fileName
* 文件名称
* @param str
* 数据内容
* @return 成功 false
*/
public static boolean saveDataStr(Context context, String fileName,
String writeStr) {
if (isNullEmptyBlank(fileName) || isNullEmptyBlank(writeStr)) {
try {
String path = context.getFilesDir().getAbsolutePath();
File file = new File(path, fileName);
if (file.exists()) {
file.delete();
}
OutputStream os = new FileOutputStream(file);
return saveOuToStr(writeStr, os);
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
} /**
* 读数据/data/data/
*
* @param context
* @param fileName
* 文件名称
* @return String 文件内容
*/
public static String readDataStr(Context context, String fileName) {
if (isNullEmptyBlank(fileName)) {
try {
String path = context.getFilesDir().getAbsolutePath();
File file = new File(path, fileName);
if (file.exists()) {
InputStream in = new FileInputStream(file);
return readInToStr(in);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
} /***************************** /data/data/图片 ************************************************************/ /**
* /data/data/存储图片
*
* @param context
* @param bitmap
* @param imageName
* 图片名
* @return 成功 false
*/
public static boolean saveDataImage(Context context, Bitmap bitmap,
String imageName) {
if (bitmap != null || isNullEmptyBlank(imageName)) {
try {
String path = context.getFilesDir().getAbsolutePath();
File file = new File(path, imageName);
if (file.exists()) {
file.delete();
}
OutputStream os = new FileOutputStream(file);
return saveOuToImage(bitmap, os);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
} /**
* /data/data/读取图片
*
* @param context
* @param imageName
* @return Bitmap
*/
public static Bitmap readDataImage(Context context, String imageName) {
if (isNullEmptyBlank(imageName)) {
try {
String path = context.getFilesDir().getAbsolutePath();
File file = new File(path, imageName);
if (file.exists()) {
InputStream in = new FileInputStream(file);
return BitmapFactory.decodeStream(in);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return null;
} /***************************** SDCard数据 *****************************************************************/ /**
* 写数据SDCard
*
* @param fileName
* 文件名称
* @param writeStr
* 数据内容
* @return 成功 false
*/
public static boolean saveSDStr(String fileName, String writeStr) {
if (isNullEmptyBlank(fileName) || isNullEmptyBlank(writeStr)) {
try {
File file = new File(isExistsFilePath(), fileName);
if (file.exists()) {// 判读文件是否存在。存在读取
file.delete();
}
OutputStream os = new FileOutputStream(file);
return saveOuToStr(writeStr, os);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
} /**
* 读取SDCard文件
*
* @param fileName
* 文件名称
* @return String 文件内容
*/
@SuppressLint("SdCardPath")
public static String readSDStr(String fileName) {
if (isNullEmptyBlank(fileName)) {
try {
String filePath = isExistsFilePath() + "/";// "/mnt/sdcard/image/"+
File file = new File(filePath);
if (file.exists()) {// 判读文件是否存在,存在读取
InputStream fin = new FileInputStream(filePath + fileName);
return readInToStr(fin);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
} /***************************** SDCard图片 *****************************************************************/ /**
* 保存到SDCard
*
* @param bitmap
* @param imageName
* 图片名
* @return 成功 false
*/
public static boolean saveSDImage(Bitmap bitmap, String imageName) {
if (isNullEmptyBlank(imageName) || bitmap != null) {
try {
File file = new File(isExistsFilePath(), imageName);
if (file.exists()) {// 判读文件是否存在,存在读取
file.delete();
}
OutputStream fos = new FileOutputStream(file);
return saveOuToImage(bitmap, fos);
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
} /**
* 获取SDCard文件
*
* @param imageName
* 图片名
* @return Bitmap
*/
public static Bitmap readSDImage(String imageName) {
if (isNullEmptyBlank(imageName)) {
String filePath = getSDPath() + CACHE + "/" + imageName;
File file = new File(filePath);
if (file.exists()) {// 判读文件是否存在,存在读取
return BitmapFactory.decodeFile(filePath);
}
}
return null;
} /***************************** 读取网络数据 *****************************************************************/ /**
* 读取网络数据
*
* @param path
* @return String
*/
public static String getNetFileString(String path) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inStream = conn.getInputStream();
return readData(inStream, CHARSETNAME);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
} private static String readData(InputStream inSream, String charsetName)
throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int len = -1;
while ((len = inSream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
} /***************************** 网络读取图片byte[] *****************************************************************/ /**
*
* @param path
* 文件路径
* @return byte[] data
*/
public static byte[] getNetImageByte(String path) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inStream = conn.getInputStream();
return readStream(inStream);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
} private static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
} /**
* 获取sd卡的缓存路径, 一般在卡中sdCard就是这个文件夹
*
* @return SDPath
*/
private static String getSDPath() {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED); // 推断sd卡是否存在
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory();// 获取根文件夹
} else {
Log.e("ERROR", "没有内存卡");
}
return sdDir.toString();
} /**
* 获取缓存文件夹文件夹 假设不存在创建 否则则创建文件夹
*
* @return filePath
*/
private static String isExistsFilePath() {
String filePath = getSDPath() + CACHE;
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
return filePath;
} private static boolean saveOuToStr(String writeStr, OutputStream os)
throws IOException, UnsupportedEncodingException {
os.write(writeStr.getBytes(CHARSETNAME));
os.flush();
os.close();
return false;
} private static String readInToStr(InputStream in) throws IOException {
int length = in.available();
byte[] buffer = new byte[length];
in.read(buffer);
in.close();
return EncodingUtils.getString(buffer, CHARSETNAME);
} private static boolean saveOuToImage(Bitmap bitmap, OutputStream fos)
throws IOException {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
return false;
} /**
* 推断字符串是否为空(包括null与""," ")
*
* @param str
* @return true 包括null与""," "
*/
private static boolean isNullEmptyBlank(String str) {
if (str == null || "".equals(str) || "".equals(str.trim())) {
return false;
}
return true;
} }

万能存储工具类SDCard存储 /data/data/存储 assets存储 raw存储的更多相关文章

  1. jquery在元素中存储数据:data()

    转自:http://www.php.cn/js-tutorial-405445.html 在元素中存储数据:data() 1 2 3 4 5 6 7 8 9 10 <!DOCTYPE html& ...

  2. Vue父子组件通信(父级向子级传递数据、子级向父级传递数据、Vue父子组件存储到data数据的访问)

    Vue父子组件通信(父级向子级传递数据.子级向父级传递数据.Vue父子组件存储到data数据的访问) 一.父级向子级传递数据[Prop]: ● Prop:子组件在自身标签上,使用自定义的属性来接收外界 ...

  3. android登录实现,存储数据到/data/data/包名/info.txt

    1.一个简单登录界面布局代码如下: @1采用线性布局加相对布局方式 @2线性布局采用垂直排列 <?xml version="1.0" encoding="utf-8 ...

  4. Android——FileOutputStream与openFileOutput()的区别分析【第一个用于文件存储,第二个用于SD卡存储】【转】

    本文实例分析了Android编程中FileOutputStream与openFileOutput()的区别.分享给大家供大家参考,具体如下: openFileOutput() 首先给大家介绍使用文件如 ...

  5. $.data(data , "")

    今天在二次开发的时候,看到源代码的新闻列表是Aajax获取的,点击新闻内容触发编辑,我没有看到新闻Id却能查到信息. 观看$.ajax遍历赋值过程中,$tr("<a>新闻内容&l ...

  6. 如何在安卓/data(而不是/data/data)目录下进行文件的读写操作

    分析:Android默认是无法直接操作/data目录的,只能读写程序自己的私有目录,也就是/data/data/package name/下,默认只能操作这个目录下的文件,也就是我们想直接读写/dat ...

  7. Android获取文件夹路径 /data/data/

    首先内部存储路径为/data/data/youPackageName/,下面讲解的各路径都是基于你自己的应用的内部存储路径下.所有内部存储中保存的文件在用户卸载应用的时候会被删除. 一. files1 ...

  8. [转帖]influxdb和boltDB简介——MVCC+B+树,Go写成,Bolt类似于LMDB,这个被认为是在现代kye/value存储中最好的,influxdb后端存储有LevelDB换成了BoltDB

    influxdb和boltDB简介——MVCC+B+树,Go写成,Bolt类似于LMDB,这个被认为是在现代kye/value存储中最好的,influxdb后端存储有LevelDB换成了BoltDB ...

  9. Android /data/data/app_file/目录下面安装apk无权限问题

    当识别SDCard的时候 String filePath = null; String state = Environment.getExternalStorageState(); if (state ...

随机推荐

  1. 236 Lowest Common Ancestor of a Binary Tree 二叉树的最近公共祖先

    给定一棵二叉树, 找到该树中两个指定节点的最近公共祖先. 详见:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tre ...

  2. CF814B An express train to reveries

    思路: 模拟,枚举. 实现: #include <iostream> using namespace std; ; int a[N], b[N], cnt[N], n, x, y; int ...

  3. vue-devtools是vue浏览器调试工具

    开vue官网在vue-生态系统-工具可以看到vue-devtools这个工具: vue-devtools是一款基于chrome游览器的插件,用于调试vue应用,这可以极大地提高我们的调试效率.接下来我 ...

  4. Android 比SwipeRefreshLayout更漂亮和强大的下拉刷新控件:Android-MaterialRefreshLayout

    这是一个下拉刷新的控件,它比SwipeRefreshLayout更加漂亮和强大.它易于使用并且支持API LEVEL >= 8.希望你能够喜欢. Now let me talk about Ma ...

  5. Android开发笔记(2)——ViewGroup

    笔记链接:http://www.cnblogs.com/igoslly/p/6794344.html 一.ViewGroup 1.ViewGroup的意义——整合Layout多个不同View,并对其进 ...

  6. 【Python-2.7】换行符和制表符

    在Python中换行符“\n”表示接下来的内容将会换到下一行显示,制表符“\t”表示下面的内容显示时在前面留出空白,如打印如下内容: Dear: I love you forever! 上面的一段话分 ...

  7. RabbitMQ系列(五)--高级特性

    在上一篇文章讲解MQ消息可靠性投递和幂等性中有提到confirm机制的重要性,现在更相信的说明一下 一.Confirm机制 Confirm就是消息确认,当Producer发送消息,如果Broker收到 ...

  8. Ceres

    sudo apt-get install liblapack-dev libsuitesparse-dev libcxspares3.1.2 libgflags-dev libggoogle-glog ...

  9. Oracle RAC 后台进程

    LMS  - Gobal         全局缓存服务进程 LMD  - Global Enqueue Service Daemon 全局查询服务守护进程 LMON -  全局服务器监控进程 LCK0 ...

  10. java基础学习日志--异常案例

    package test7; public class InvalidScroreException extends Exception { public InvalidScroreException ...