
文件存储是 AndroID 中最基本的一种数据存储方式,它不对存储的内容进行任何的格式化处理,所有数据都是原封不动的保存到文件当中的。
概述
文件存取的核心就是输入流和输出流。
AndroID文件的 *** 作模式
文件的相关 *** 作方法
文件读写的实现
openfileOutput和openfileinput方法
/** * openfileOutput,openfileinput * 这两种方法同sp一样只能讲文件保存到手机内存固定的路径中, * 默认为 /data/data/<packagename>/files */ private voID save2file() { try { //向文件写入内容 fileOutputStream os = openfileOutput("file.txt",Context.MODE_PRIVATE); String text = "写数据到文件"; os.write(text.getBytes("utf-8")); //关闭流 os.close(); } catch (fileNotFoundException e) { e.printstacktrace(); } catch (UnsupportedEnCodingException e) { e.printstacktrace(); } catch (IOException e) { e.printstacktrace(); } } /** * */ private voID readfile() { try { fileinputStream ins = openfileinput("file.txt"); byte[] buffer = new byte[100]; int byteCount = ins.read(buffer); String text = new String(buffer,byteCount,"utf-8"); Toast.makeText(this,text,Toast.LENGTH_SHORT).show(); ins.close(); } catch (fileNotFoundException e) { e.printstacktrace(); } catch (IOException e) { e.printstacktrace(); } }文件存储位置
/data/data/<package-name>/files目录下
openfileOutput和openfileinput方法可以获得 *** 作文件的OutputStream以及inputStream对象,而且可以通过流对象处理任何文件的数据,但是这两个方法同SharedPreferences一样,只能在手机内存卡的指定目录建立文件,因此在使用上仍然有一定的局限性。
读取SD卡上的文件
main_activity.xml:
<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:ID="@+ID/linearLayout1" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" tools:context="com.jay.example.filedemo2.MainActivity"> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="清输入文件名" /> <EditText androID:ID="@+ID/editTitle" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:hint="文件名" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="清输入文件内容" /> <EditText androID:ID="@+ID/editdetail" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:hint="文件内容" /> <button androID:ID="@+ID/btnsave" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="保存到SD卡" /> <button androID:ID="@+ID/btnclean" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="清空" /> <button androID:ID="@+ID/btnread" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="读取sd卡中的文件" /></linearLayout>
接着我们来写一个SD *** 作类: SDfileHelper.Java
public class SDfileHelper { private Context context; public SDfileHelper() { } public SDfileHelper(Context context) { super(); this.context = context; } //往SD卡写入文件的方法 public voID savafileToSD(String filename,String filecontent) throws Exception { //如果手机已插入sd卡,且app具有读写sd卡的权限 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename; //这里就不要用openfileOutput了,那个是往手机内存中写数据的 fileOutputStream output = new fileOutputStream(filename); output.write(filecontent.getBytes()); //将String字符串以字节流的形式写入到输出流中 output.close(); //关闭输出流 } else Toast.makeText(context,"SD卡不存在或者不可读写",Toast.LENGTH_SHORT).show(); } //读取SD卡中文件的方法 //定义读取文件的方法: public String readFromSD(String filename) throws IOException { StringBuilder sb = new StringBuilder(""); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename; //打开文件输入流 fileinputStream input = new fileinputStream(filename); byte[] temp = new byte[1024]; int len = 0; //读取文件内容: while ((len = input.read(temp)) > 0) { sb.append(new String(temp,len)); } //关闭输入流 input.close(); } return sb.toString(); }}接着MainActivity.java实现相关逻辑:
public class MainActivity extends AppCompatActivity implements VIEw.OnClickListener{ private EditText editname; private EditText editdetail; private button btnsave; private button btnclean; private button btnread; private Context mContext; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); mContext = getApplicationContext(); bindVIEws(); } private voID bindVIEws() { editname = (EditText) findVIEwByID(R.ID.editTitle); editdetail = (EditText) findVIEwByID(R.ID.editdetail); btnsave = (button) findVIEwByID(R.ID.btnsave); btnclean = (button) findVIEwByID(R.ID.btnclean); btnread = (button) findVIEwByID(R.ID.btnread); btnsave.setonClickListener(this); btnclean.setonClickListener(this); btnread.setonClickListener(this); } @OverrIDe public voID onClick(VIEw v) { switch (v.getID()){ case R.ID.btnclean: editdetail.setText(""); editname.setText(""); break; case R.ID.btnsave: String filename = editname.getText().toString(); String filedetail = editdetail.getText().toString(); SDfileHelper sdHelper = new SDfileHelper(mContext); try { sdHelper.savafileToSD(filename,filedetail); Toast.makeText(getApplicationContext(),"数据写入成功",Toast.LENGTH_SHORT).show(); } catch(Exception e){ e.printstacktrace(); Toast.makeText(getApplicationContext(),"数据写入失败",Toast.LENGTH_SHORT).show(); } break; case R.ID.btnread: String detail = ""; SDfileHelper sdHelper2 = new SDfileHelper(mContext); try { String filename2 = editname.getText().toString(); detail = sdHelper2.readFromSD(filename2); } catch(IOException e){e.printstacktrace();} Toast.makeText(getApplicationContext(),detail,Toast.LENGTH_SHORT).show(); break; } }}最后别忘记在AndroIDManifest.xml写上读写SD卡的权限哦!
<!-- 在SDCard中创建与删除文件权限 --><uses-permission androID:name="androID.permission.MOUNT_UNMOUNT_fileSYstemS"/><!-- 往SDCard写入数据权限 --><uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/>
如何判断虚拟和物理两种SDK
在默认情况下,会将一部分存储空间分给虚拟的SD卡使用(一部分用于安装AndroID *** 作系统)
androID.os.Enviroment.isExternalStorageRemovalbe()
返回true:SD卡是物理的,反之SD卡是虚拟的。
用于适配不同型号手机,反射获取SD卡路径和状态
package com.turing.base.activity.dataStore.fileStore;import androID.content.Context;import androID.os.Environment;import androID.os.StatFs;import androID.os.storage.StorageManager;import androID.text.TextUtils;import androID.util.Log;import java.io.file;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.concurrent.ConcurrentlinkedQueue;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * 用于适配不同型号手机,反射获取SD卡路径和状态 * */public class DevMountInfo { private final String TAG = DevMountInfo.class.getSimplename(); private static final int ERROR = -1; // class name private final static String CLASS_name = "androID.os.storage.StorageVolume"; //remained spare memory size private static final int REMAINED_SPARE_IN_MB = 100; // method name private final static String METHOD_GET_VolUME_List = "getVolumeList"; private final static String METHOD_GET_VolUME_STATE = "getVolumeState"; private final static String METHOD_IS_REMOVABLE = "isRemovable"; private final static String METHOD_GET_PATH = "getPath"; private final static String MOUNTED = "mounted"; private static DevMountInfo INSTANCE; private String mSDCardpath = null; // internal file path private ConcurrentlinkedQueue<String> mInternalPathList = new ConcurrentlinkedQueue<String>(); // external file path private ConcurrentlinkedQueue<String> mExternalPathList = new ConcurrentlinkedQueue<String>(); private ExecutorService mExecutor = null; private DevMountInfo() { mExecutor = Executors.newSingleThreadExecutor(); } public static DevMountInfo getInstance() { synchronized (DevMountInfo.class) { if (null == INSTANCE) { INSTANCE = new DevMountInfo(); } return INSTANCE; } } @OverrIDe protected voID finalize() throws Throwable { super.finalize(); synchronized (DevMountInfo.class) { mInternalPathList.clear(); mExternalPathList.clear(); mExecutor.shutdown(); INSTANCE = null; } } public voID init(final Context context) { mExecutor.execute(new Runnable() { @OverrIDe public voID run() { executeInit(context); } }); } public boolean isSDCardFull() { return REMAINED_SPARE_IN_MB > (getSDCardAvailSpace() * 1024); } public boolean isSDCardAvaiable() { return !mExternalPathList.isEmpty() || !mInternalPathList.isEmpty(); } public String getSDCardpath() { return mSDCardpath; } public long getSDCardTotalSpace() { long totalSpace = 0; if (!TextUtils.isEmpty(mSDCardpath)) { StatFs sf = new StatFs(mSDCardpath); long blockSize = sf.getBlockSize(); long total = sf.getBlockCount(); totalSpace = total * blockSize / 1024; } return totalSpace; } public long getSDCardAvailSpace() { long availSpace = 0; if (!TextUtils.isEmpty(mSDCardpath)) { StatFs sf = new StatFs(mSDCardpath); long blockSize = sf.getBlockSize(); long availCount = sf.getAvailableBlocks(); availSpace = availCount * blockSize / 1024; } return availSpace; } public String getInternalSDCardpath() { return mInternalPathList.peek(); } public String getExternalSDCardpath() { return mExternalPathList.peek(); } private voID executeInit(Context context) { StorageManager mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); if (mStorageManager != null) { Class<?> mStorageVolume = null; Method mGetVolumeListMethod = null; Method mGetVolumeStateMethod = null; Method mGetPathMethod = null; Method mIsRemovableMethod = null; Object[] mStorageVolumeList = null; try { mStorageVolume = Class.forname(CLASS_name); mGetVolumeListMethod = mStorageManager.getClass().getmethod(METHOD_GET_VolUME_List,new Class[0]); mGetVolumeStateMethod = mStorageManager.getClass().getmethod(METHOD_GET_VolUME_STATE,new Class[]{String.class}); mIsRemovableMethod = mStorageVolume.getmethod(METHOD_IS_REMOVABLE,new Class[0]); mGetPathMethod = mStorageVolume.getmethod(METHOD_GET_PATH,new Class[0]); mStorageVolumeList = (Object[]) mGetVolumeListMethod.invoke(mStorageManager,new Object[0]); boolean mIsRemovable = false; if (mStorageVolumeList != null && mStorageVolumeList.length > 0) { int mStorageVolumeCount = mStorageVolumeList.length; Log.i(TAG,"init() === > StorageVolume Count = " + mStorageVolumeCount); mInternalPathList.clear(); mExternalPathList.clear(); for (int i = 0; i < mStorageVolumeCount; ++i) { String mStoragePath = (String) mGetPathMethod.invoke(mStorageVolumeList[i],new Object[0]); mIsRemovable = ((Boolean) mIsRemovableMethod.invoke(mStorageVolumeList[i],new Object[0])).booleanValue(); if (!TextUtils.isEmpty(mStoragePath)) { String state = (String) mGetVolumeStateMethod.invoke(mStorageManager,new Object[]{mStoragePath}); if ((state != null) && (state.equals(MOUNTED))) { if (mIsRemovable) { Log.i(TAG,"init() === > external storage path = (" + mStoragePath + ")"); mExternalPathList.add(mStoragePath); } else { Log.i(TAG,"init() === > internal storage path = (" + mStoragePath + ")"); mInternalPathList.add(mStoragePath); } } } } } } catch (ClassNotFoundException e) { handleInvalID(); Log.e(TAG,"init() === > Exception:ClassNotFoundException"); } catch (NoSuchMethodException e) { handleInvalID(); Log.e(TAG,"init() === > Exception:NoSuchMethodException"); } catch (IllegalArgumentException e) { handleInvalID(); Log.e(TAG,"init() === > Exception:IllegalArgumentException"); } catch (illegalaccessexception e) { handleInvalID(); Log.e(TAG,"init() === > Exception:illegalaccessexception"); } catch (InvocationTargetException e) { handleInvalID(); Log.e(TAG,"init() === > Exception:InvocationTargetException"); } } else { handleInvalID(); Log.e(TAG,"init() === > can't get storage manager"); } initSDCardpath(); } private voID handleInvalID() { mInternalPathList.add(Environment.getExternalStorageDirectory().getPath()); } private voID initSDCardpath() { if (!mExternalPathList.isEmpty()) { mSDCardpath = mExternalPathList.peek(); } else if (!mInternalPathList.isEmpty()) { mSDCardpath = mInternalPathList.peek(); } else { mSDCardpath = Environment.getExternalStorageDirectory().getPath(); } Log.i(TAG,"initSDCardpath() === > SDCARD PATH = (" + mSDCardpath + ")"); } /** * SDCARD是否存 */ public static boolean externalMemoryAvailable() { return androID.os.Environment.getExternalStorageState().equals( androID.os.Environment.MEDIA_MOUNTED); } /** * 获取手机内部剩余存储空间 * * @return */ public static long getAvailableInternalMemorySize() { file path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } /** * 获取手机内部总的存储空间 * * @return */ public static long getTotalinternalMemorySize() { file path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } /** * 获取手机内置存储剩余存储空间 * * @return */ public static long getAvailableInternalSystemMemorySize() { file path = Environment.getRootDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } /** * 获取手机内置存储总的存储空间 * * @return */ public static long getTotalinternalSystemMemorySize() { file path = Environment.getRootDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } /** * 获取SDCARD剩余存储空间 * * @return */ public static long getAvailableExternalMemorySize() { if (externalMemoryAvailable()) { file path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } else { return ERROR; } } /** * 获取SDCARD总的存储空间 * * @return */ public static long getTotalExternalMemorySize() { if (externalMemoryAvailable()) { file path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return totalBlocks * blockSize; } else { return ERROR; } } public static long getAvailableMemorySize(String path) { if (null == path) return 0; StatFs stat = new StatFs(path); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; }}读取raw和assets文件夹下的文件
相信大家对两个文件夹并不陌生,如果我们不想自己的文件被编译成二进制文件的话, 我们可以把文件放到这两个目录下,而两者的区别如下:
res/raw:文件会被映射到R.java文件中,访问的时候直接通过资源ID即可访问,而且 他不能有目录结构,就是不能再创建文件夹 assets:不会映射到R.java文件中,通过AssetManager来访问,能有目录结构,即, 可以自行创建文件夹。读取文件资源:
res/raw:
inputStream is =getResources().openRawResource(R.raw.filename);
assets:
AssetManager am = getAssets(); inputStream is = am.open("filename");SAX引擎读取XML文件
sax引擎读取xml文件的原理:
sax技术在处理xml文件时并不一次性把xml文件装入内存,而是一边读一般解析。
使用sax处理xml需要一个Handler对象,一般会使用org.xml.sax.helpers.DefaultHandler的子类作为Handler对象
因此,这就需要处理如下5个分析点,也可称为分析事件:
开始分析xml文件。该分析点表示sax引擎刚开始处理xml文件,还没有读取xml文件中的内容。该分析点对应于DefaultHandler类中的startdocument()事件方法,可以在该方法中做一下初始化的工作! 开始处理每一个xml元素,也就是遇到<product>,<item>这样的起始标记,sax引擎每次扫描到新的xml元素的起始标记会触发这个分析事件,对应的事件分析方法是startElement,在该方法中可以获取当前元素的名称和元素属性的相关信息 处理完一个xml元素,也就是遇到</product>,</item>这样的结束标记,该分析点对应的事件方法是endElement,在该事件中可以获得当前处理完的元素的全部信息。 处理完xml文件。如果sax引擎将整个xml文件的内容都扫描完了,就到了这个分析点,该分析点对应的事件方法enddocument(),该事件方法可能不是必需的,如果最后有以下收尾工作,如释放一下资源,可以在该方法中完成! 读取字符分析点。这是最重要的分析点。如果没有这个分析点,前4步的处理相当于白跑一遍,虽然读取了xml文件中的所有内容,但并未保存这些内容,而这个分析点所对应的characters事件方法的主要作用就是保存sax引擎读取的xml文件中的内容。更准确地说是保存xml元素的文本,也就是<product>abc</product>中的abc。Code
res\raw\product.xml
<?xml version="1.0" enCoding="utf-8"?><products> <product> <ID>10</ID> <name>电脑</name> <price>2067.25</price> </product> <product> <ID>20</ID> <name>微波炉</name> <price>520</price> </product> <product> <ID>30</ID> <name>洗衣机</name> <price>2400</price> </product></products>
Product.java
public class Product{ private int ID; private String name; private float price; public int getID() { return ID; } public voID setID(int ID) { this.ID = ID; } public String getname() { return name; } public voID setname(String name) { this.name = name; } public float getPrice() { return price; } public voID setPrice(float price) { this.price = price; }}XML2Product.java(DefaultHandler子类)
DefaultHandler子类 ,核心类,负责处理分析点事件。
import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import java.util.ArrayList;import java.util.List;public class XML2Product extends DefaultHandler { private List<Product> products; private Product product; private StringBuffer buffer = new StringBuffer(); public List<Product> getProducts() { return products; } @OverrIDe public voID characters(char[] ch,int start,int length) throws SAXException { buffer.append(ch,start,length); super.characters(ch,length); } @OverrIDe public voID startdocument() throws SAXException { // 开始分析xml文件,创建List对象用于保存分析完的Product对象 products = new ArrayList<Product>(); } @OverrIDe public voID startElement(String uri,String localname,String qname,Attributes attributes) throws SAXException { if (localname.equals("product")) { // 如果分析的是<product>标签,则创建一个Product对象 product = new Product(); } super.startElement(uri,localname,qname,attributes); } @OverrIDe public voID endElement(String uri,String qname) throws SAXException { if (localname.equals("product")) { // 处理完 <product>标签后 将product对象添加到products中 products.add(product); } else if (localname.equals("ID")) { // 设置ID属性的值 product.setID(Integer.parseInt(buffer.toString().trim())); // 将标签内容的缓存区清空 buffer.setLength(0); } else if (localname.equals("name")) { product.setname(buffer.toString().trim()); buffer.setLength(0); } else if (localname.equals("price")) { product.setPrice(float.parsefloat(buffer.toString().trim())); buffer.setLength(0); } super.endElement(uri,qname); }}Xml2JavaObjectAct
import androID.app.AlertDialog;import androID.os.Bundle;import androID.support.v7.app.AppCompatActivity;import androID.util.Xml;import androID.vIEw.VIEw;import com.turing.base.R;import java.io.inputStream;import java.util.List;public class Xml2JavaObjectAct extends AppCompatActivity { @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_xml2_java_object); } public voID onClick_XMLToObject(VIEw vIEw) { try { // 打开资源文件 inputStream is = getResources().openRawResource(R.raw.products); XML2Product xml2Product = new XML2Product(); // 开始分析prIDucts.xml文件 androID.util.Xml.parse(is,Xml.EnCoding.UTF_8,xml2Product); // 输出转换后的java对象 List<Product> products = xml2Product.getProducts(); String msg = "共" + products.size() + "个产品\n"; for (Product product : products) { msg += "ID:" + product.getID() + " 产品名:" + product.getname() + " 价格:" + product.getPrice() + "\n"; } // d出对话框 new AlertDialog.Builder(this).setTitle("产品信息").setMessage(msg) .setPositivebutton("关闭",null).show(); } catch (Exception e) { } }}效果图
Code
activity_jar_zip.xml
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:layout_wIDth="fill_parent" androID:layout_height="fill_parent" androID:orIEntation="vertical" > <button androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:onClick="onClick_Jar_Compress" androID:text="用jar格式压缩文件" /> <button androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:onClick="onClick_Jar_Uncompress" androID:text="解压jar格式文件" /> <button androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:onClick="onClick_Zip_Compress" androID:text="用zip格式压缩文件" /> <button androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:onClick="onClick_Zip_Uncompress" androID:text="解压zip格式文件" /></linearLayout>
JarZipAct
import androID.os.Bundle;import androID.support.v7.app.AppCompatActivity;import androID.vIEw.VIEw;import androID.Widget.Toast;import com.turing.base.R;import java.io.file;import java.io.fileinputStream;import java.io.fileOutputStream;import java.io.inputStream;import java.util.jar.JarEntry;import java.util.jar.JarinputStream;import java.util.jar.JarOutputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipinputStream;import java.util.zip.ZipOutputStream;public class JarZipAct extends AppCompatActivity { @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_jar_zip); } public voID onClick_Jar_Compress(VIEw vIEw) { try { // 使用fileOutputStream对象指定一个要输出的压缩文件(file.jar) fileOutputStream fos = new fileOutputStream( androID.os.Environment.getExternalStorageDirectory() + "/file.jar"); // 第一步 创建JarOutputStream对象 JarOutputStream jos = new JarOutputStream(fos); // 第二步 创建一个JarEntry对象,并指定待压缩文件在压缩包中的文件名 JarEntry jarEntry = new JarEntry("strings.xml"); jos.putNextEntry(jarEntry); inputStream is = getResources().getAssets().open("strings.xml"); byte[] buffer = new byte[8192]; int count = 0; // 第四步 写入数据 while ((count = is.read(buffer)) >= 0) { jos.write(buffer,count); } // 第五步 关闭当前的JarEntry等对象 is.close(); jos.closeEntry(); jos.close(); Toast.makeText(this,"成功将strings.xml文件以jar格式压缩.",Toast.LENGTH_LONG) .show(); } catch (Exception e) { Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show(); } } public voID onClick_Jar_Uncompress(VIEw vIEw) { try { // 定义要解压的文件 String filename = androID.os.Environment .getExternalStorageDirectory() + "/file.jar"; if (!new file(filename).exists()) { Toast.makeText(this,"压缩文件不存在.",Toast.LENGTH_LONG).show(); return; } // 使用fileinputStream对象指定要解压的对象 fileinputStream fis = new fileinputStream(filename); // 1 创建JarinputStream对象来读取压缩文件(file.jar) JarinputStream jis = new JarinputStream(fis); // 2 调用getNextJarEntry方法打开压缩包中的第一个文件 ,如果有多个,多次调用该方法 JarEntry jarEntry = jis.getNextJarEntry(); // 3 输出已解压的文件 fileOutputStream fos = new fileOutputStream( androID.os.Environment.getExternalStorageDirectory() + "/" + jarEntry.getname()); byte[] buffer = new byte[8192]; int count = 0; // 4 输出已解压的字节流 while ((count = jis.read(buffer)) >= 0) { fos.write(buffer,count); } // 5 关闭 jis.closeEntry(); jis.close(); fos.close(); Toast.makeText(this,"成功解压jar格式的文件.",Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(this,Toast.LENGTH_LONG).show(); } } public voID onClick_Zip_Compress(VIEw vIEw) { try { // 指定了2个待压缩的w文件,都在assets目录中 String[] filenames = new String[] {"main.xml","strings.xml"}; fileOutputStream fos = new fileOutputStream( androID.os.Environment.getExternalStorageDirectory() + "/file.zip"); ZipOutputStream zos = new ZipOutputStream(fos); int i = 1; //枚举filenames中的所有待压缩文件 while (i <= filenames.length) { // 从filenames数组中取出当前待压缩的温佳明,作为压缩后的文件名,以保持要说前后文件名称一致 ZipEntry zipEntry = new ZipEntry(filenames[i - 1]); // 打开当前的ZipEntry对象 zos.putNextEntry(zipEntry); inputStream is = getResources().getAssets().open( filenames[i - 1]); byte[] buffer = new byte[8192]; int count = 0; // 写入数据 while ((count = is.read(buffer)) >= 0) { zos.write(buffer,count); } zos.flush(); // 关闭当前的ZipEntry对象 zos.closeEntry(); is.close(); i++; } zos.finish(); zos.close(); Toast.makeText(this,"成功将main.xml、strings.xml文件以zip格式压缩.",Toast.LENGTH_LONG).show(); } } public voID onClick_Zip_Uncompress(VIEw vIEw) { try { // 指定待解压的文件 String filename = androID.os.Environment .getExternalStorageDirectory() + "/file.zip"; if (!new file(filename).exists()) { Toast.makeText(this,Toast.LENGTH_LONG).show(); return; } fileinputStream fis = new fileinputStream(filename); ZipinputStream zis = new ZipinputStream(fis); ZipEntry zipEntry = null; // 通过不断调用getNextEntry方法来解压file.zip中所有的文件 while ((zipEntry = zis.getNextEntry()) != null) { fileOutputStream fos = new fileOutputStream( androID.os.Environment.getExternalStorageDirectory() + "/" + zipEntry.getname()); byte[] buffer = new byte[8192]; int count = 0; while ((count = zis.read(buffer)) >= 0) { fos.write(buffer,count); } zis.closeEntry(); fos.close(); } zis.close(); Toast.makeText(this,Toast.LENGTH_LONG).show(); } }}原文链接:http://blog.csdn.net/yangshangwei/article/details/50831269
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的android数据存储之文件存储方法全部内容,希望文章能够帮你解决android数据存储之文件存储方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)