1.SharedPreferences 主要用于引导页,少量信息保存;
package myapplication.com.myapp.Utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Administrator on 2016/8/9.
*/
public class SharedPreferencesUtils {
private static String NAME="share_data";
public static void setParam(Context context, String key, Object object){
SharedPreferences p=context.getSharedPreferences(NAME,Context.MODE_APPEND);
String type=object.getClass().getSimpleName();
SharedPreferences.Editor editor=p.edit();
if(type.equals("String")){
editor.putString(key,(String)object);
}
else if(type.equals("Integer")){
editor.putInt(key,(Integer) object);
}
else if(type.equals("Boolean")){
editor.putBoolean(key,(Boolean) object);
}else if(type.equals("Long")){
editor.putLong(key,(Long)object);
}
editor.commit();
}
public static Object getParam(Context context,String key,Object object){
SharedPreferences p=context.getSharedPreferences(NAME,Context.MODE_APPEND);
String type=object.getClass().getSimpleName();
if(type.equals("String")){
return p.getString(key,(String)object);
}
else if(type.equals("Integer")){
return p.getInt(key,(Integer)object);
} else if (type.equals("Boolean")) {
return p.getBoolean(key, (Boolean) object);
} else if (type.equals("Long")) {
return p.getLong(key, (Long) object);
}
return null;
}
// SharePreferenceUtils.setParam(getApplicationContext(), "is_first", true);//
// boolean is_first= (boolean) SharePreferenceUtils.getParam(getApplicationContext(),"is_first",false);
}
2. 保存txt文件,读取txt文件
public class SaveFile {
/***
* @param str 需要写入的字符串
* @param filename 创建的文件名,需要包含后缀
*/
public static void Save(String str, String filename) {
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
/**
* //获取SDCard目录,
* 2.2的时候为:/mnt/sdcart
* 2.1的时候为:/sdcard,
* */
File sdCardDir = Environment.getExternalStorageDirectory();
/**
* 这里的MyjizhanFile为创建的文件夹,在根目录下
* */
File filedir = new File(sdCardDir + File.separator + "MyjizhanFile");
if (!filedir.exists()) {
filedir.mkdirs();
}
/**
* 数据保存在文件中
* */
File saveFile = new File(filedir, filename);
/***
* fileOutStream 这里面的true设置可以实现连续写入,如果不设置true则只能写入一次。
* */
FileOutputStream outStream = new FileOutputStream(saveFile, true);
outStream.write(str.getBytes());
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取时间日期
*/
public static String FileName() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String filename = sdf.format(date) + ".txt";
return filename;
}
/**
* @param fileaddress 读取文件的路径+文件名
*/
public static String Readfile(String fileaddress) {
try {
File urlFile = new File(fileaddress);
InputStreamReader isr = new InputStreamReader(new FileInputStream(urlFile), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String str = "";
String mimeTypeLine = null;
while ((mimeTypeLine = br.readLine()) != null) {
str = str + mimeTypeLine;
}
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3. SDcardHelper工具类
package myapplication.com.myapp.Utils;
import android.os.Environment;
import android.os.StatFs;
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.util.ArrayList;
import java.util.List;
import myapplication.com.myapp.bean.WenjianInfo;
public class SDcardHelper {
/**
*
*
* 判断sdcard是否挂载,可用
* */
public static boolean isSDcardMounted() {
boolean state = Environment.getExternalStorageState().
equals(Environment.MEDIA_MOUNTED);
return state;
}
/**
* 获取sdcard的路径
*
*/
public static String getSDCardPath() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
return path;
}
/**
* 获取sdcard的大小
*
*/
public static long getSDCardSize() {
if (isSDcardMounted()) {
//
StatFs sf = new StatFs(getSDCardPath());
long count = sf.getBlockCount();
long size = sf.getBlockSize();
return count * size;
}
return 0;
}
/**
* 获取sdcard的空余空间大小
*/
public static long getSDCardFreeSize() {
if (isSDcardMounted()) {
StatFs sFs = new StatFs(getSDCardPath());
long count = sFs.getFreeBlocks();
long size = sFs.getBlockSize();
return count * size;
}
return 0;
}
/**
* 获取sdcard的可利用空间大小
*/
public static long getSDCardAvailableSize() {
if (isSDcardMounted()) {
StatFs sFs = new StatFs(getSDCardPath());
long count = sFs.getAvailableBlocks();
long size = sFs.getBlockSize();
return count * size;
}
return 0;
}
/**
* 保存文件到sdcard
* @param data 保存目标数组
* @param dir 保存路径
* @param filename 文件名
* @return
*/
public static boolean saveFileToSDCard(byte[] data, String dir,String filename) {
if (isSDcardMounted()) {
File filedir = new File(getSDCardPath() + File.separator + dir);
if (!filedir.exists()) {
filedir.mkdirs();
}
if (getSDCardAvailableSize() >= data.length) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filedir+File.separator+filename));
fos.write(data);
fos.flush();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
return false;
}
/**
* 从sdcard路径读取文件 ,返回字符数组
*
*/
public static byte[] readFileFromSDCard(String filepath) {
if (isSDcardMounted()) {
File file = new File(filepath);
ByteArrayOutputStream byteArrayOutputStream = null;
if (file.exists()) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = fileInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
return byteArrayOutputStream.toByteArray();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
return null;
}
/**
* 保存文件到sdcard
* @param data 保存目标数组
* @param dir 保存路径
* @param filename 文件名
* @return
*/
public static boolean saveFileToSDCard1(byte[] data, String dir,String filename) {
if (isSDcardMounted()) {
File filedir = new File(getSDCardPath() + File.separator + dir);
if (!filedir.exists()) {
filedir.mkdirs();
}
if (getSDCardAvailableSize() >= data.length) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filedir+File.separator+filename));
fos.write(data);
fos.flush();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
return false;
}
/**
*
* 读取文件夹下所有文件
* */
public static List<WenjianInfo> getFileName(File[] files) {
String address="";
List<WenjianInfo>data=new ArrayList<>();
if (files != null)
{
for (File file : files) {
if (file.isDirectory()) {
getFileName(file.listFiles());
} else {
String fileName = file.getName();
address=file.getAbsolutePath();
data.add(new WenjianInfo(fileName,address));
}
}
}
return data;
}
}
4.SqliteDB_Helper 工具 配合bean+dao类使用
package myapplication.com.myapp.Utils;
import android.database.sqlite.SQLiteDatabase;
import java.io.File;
/**
* Created by Administrator on 2017/1/5.
*/
public class SqliteDB_Helper {
private static String DB_PATH = SDcardHelper.getSDCardPath();
private static String DB_NAME = "jizhan.db";
static {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH+ File.separator+DB_NAME, null);
db.execSQL("create table if not exists jizhan(Cellname varchar(150)," +
"Longitude varchar(50)," +
"Latitude varchar(50)," +
"PCI varchar(40))");
db.close();
}
public static SQLiteDatabase getSqLiteDatabase() {
return SQLiteDatabase.openOrCreateDatabase(DB_PATH+File.separator+DB_NAME, null);
}
}
/**
*
* 基站数据info
* Created by gxw on 2017/1/5.
*/
public class JiZhanInfo {
private String Longitude;
private String Latitude;
private String Cellname;
private String PCI;
public JiZhanInfo( String cellname,String longitude, String latitude, String PCI) {
Longitude = longitude;
Latitude = latitude;
Cellname = cellname;
this.PCI = PCI;
}
public String getLongitude() {
return Longitude;
}
public String getLatitude() {
return Latitude;
}
public String getCellname() {
return Cellname;
}
public String getPCI() {
return PCI;
}
}
package myapplication.com.myapp.bean;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import myapplication.com.myapp.Utils.SqliteDB_Helper;
/**
* 基站
* Created by gxw on 2017/1/5.
*/
public class JiZhanInfoDao {
private static final String TAG = "JiZhanInfoDao";
/**
*
* 插入数据
* */
public boolean insert(JiZhanInfo jiZhanInfo) {
SQLiteDatabase db = SqliteDB_Helper.getSqLiteDatabase();
try {
db.execSQL("insert into jizhan (Cellname,Longitude,Latitude,PCI) values(?,?,?,?)",
new Object[]{jiZhanInfo.getCellname(),jiZhanInfo.getLongitude(),jiZhanInfo.getLatitude(),jiZhanInfo.getPCI()});
db.close();
return true;
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
/**
* 查找所有基站信息
* */
public List<JiZhanInfo> findAll() {
List<JiZhanInfo> list = new ArrayList<JiZhanInfo>();
SQLiteDatabase db = SqliteDB_Helper.getSqLiteDatabase();
/**
* db.rawQuery("select * from 表名 orderby KEY_ENDTIME",null);
* KEY_ENDTIME ASC 升序
* KEY_ENDTIME DESC 降序
* */
Cursor cursor = db.rawQuery("select * from jizhan order by PCI ASC",null);
JiZhanInfo jiZhanInfo = null;
while (cursor.moveToNext()) {
String Longitude=cursor.getString(cursor.getColumnIndex("Longitude"));
Log.i(TAG, "findAll: "+cursor.getColumnIndex("Latitude"));
Log.i(TAG, "findAll: "+cursor.getColumnIndex("Cellname"));
Log.i(TAG, "findAll: "+cursor.getColumnIndex("PCI"));
String Latitude=cursor.getString(cursor.getColumnIndex("Latitude"));
String Cellname=cursor.getString(cursor.getColumnIndex("Cellname"));
String PCI=cursor.getString(cursor.getColumnIndex("PCI"));
jiZhanInfo = new JiZhanInfo(Cellname,Longitude,Latitude,PCI);
list.add(jiZhanInfo);
}
return list;
}
}
5.Toast使用
public class ToastUtils {
private static Toast toast;
public static void showToast(Context context,String string){
if(toast==null){
toast=Toast.makeText(context, string,Toast.LENGTH_SHORT);
}else{
toast.setText(string);
}
toast.show();
}
}
6.获取file路径下所有文件
public static void getFileName(File[] files) {
String address="";
if (files != null)// 先判断目录是否为空,否则会报空指针
{
for (File file : files) {
if (file.isDirectory()) {
getFileName(file.listFiles());
} else {
String fileName = file.getName();
address=file.getAbsolutePath();
// HashMap map = new HashMap();
System.out.println("***address:"+address);
System.out.println("***name:"+fileName);
}
}
}
}
// 获得SD卡路径
File file1=new File(Environment.getExternalStorageDirectory()+File.separator+"AA");
File[] files = file1.listFiles();// 读取
Utils.getFileName(files);
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>