简单的网络数据用文件来缓存

package com.bruce.brucedemo.file.cache;


import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bruce.brucedemo.R;
import com.bruce.brucedemo.utils.Logs;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class FileCacheActivity extends FragmentActivity implements View.OnClickListener {
    private Button mGetHttpDataBtn;
    private TextView mShowDataText;
    //获取内部存储的绝对路径
    File cacheFilePath;
    private String typeId = "T1348647909107";//文章类型id,也作为缓存文件名字
    private int mPageSize = 20;//每页大小
    private int mCurrentPage = 0;//当前页

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_file_cache);
        mGetHttpDataBtn = (Button) findViewById(R.id.getdata_http_btn);
        mShowDataText = (TextView) findViewById(R.id.show_http_data_text);
        cacheFilePath = getFilesDir();// 内部文件路径
        mGetHttpDataBtn.setOnClickListener(this);//给按钮加间听
    }

    @Override
    public void onClick(View v) {

//        String httpUrl = "http://c.m.163.com/nc/article/headline/T1348647909107/0-20.html";
        String httpUrl = "http://c.m.163.com/nc/article/headline/" + typeId + "/" + mCurrentPage * mPageSize + "-" + mPageSize + ".html";
        File fileDir = getFilesDir();//内部文件路径
        File mCacheFile = new File(fileDir.getAbsolutePath(), typeId);//得到文件
/**
 * 判断缓存文件是否存在,不为空,是文件(不是目录)
 */
        if (mCacheFile != null && mCacheFile.exists() && mCacheFile.isFile()) {
            //调用readFileCache方法。从文件读取数据
            String string = readFileCache(mCacheFile);
            if (string != null && !string.equals("")) {
                mShowDataText.setText(string);
            } else {
                getHttpData(httpUrl.trim());
                Logs.w("字符串为空,执行了getHttpData<><>");
            }
        } else {
            getHttpData(httpUrl.trim());
            Logs.w("文件为空,执行了getHttpData<><>");
        }

    }

    public void getHttpData(final String httpUrl) {
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(this, httpUrl, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, String str) {
                mShowDataText.setText(str);
                writeFileCache(str, typeId);
                Logs.w("执行了writeFileCache<><>");
            }

            @Override
            public void onFailure(Throwable throwable, String s) {
                super.onFailure(throwable, s);
            }
        });
    }

    /**
     * 写字符串到文件
     *
     * @param content
     * @param name
     * @return
     */
    public File writeFileCache(String content, String name) {
        Logs.w("writeFileCache>>>FileOutputStream>>name>>>" + name);
        File fileDir = getFilesDir();//内部文件路径
        File mCacheFile = new File(fileDir.getAbsolutePath(), typeId);//typeId。以typeId为文件名

        try {
//            mCacheFile.mkdir();//这是创建文件夹
            if (mCacheFile.isDirectory()) {//若是目录就删除
                mCacheFile.delete();
            }
            mCacheFile.createNewFile();//创建新文件

            FileOutputStream outputStream = new FileOutputStream(mCacheFile);
            outputStream.write(content.getBytes());//将数据通过FileOutputStream写到文件里面
            String packName = outputStream.getClass().getPackage().getName();
            outputStream.close();
            Logs.w("writeFileCache>>>FileOutputStream>>" + packName);
        } catch (IOException e) {
            Logs.w("writeFileCache错误" + e.toString());
            e.printStackTrace();
        }

        return mCacheFile;
    }

    /**
     * 从文件读取数据(字符串)
     *
     * @param file
     * @return
     */
    public String readFileCache(File file) {
        String str = "";
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            // size  为字串的长度 ,这里一次性读完,就是FileInputStream流的大小,
            int size = in.available();
            byte[] buffer = new byte[size];
            int i = in.read(buffer);
            in.close();
            str = new String(buffer, "utf-8");
            Logs.w("文件读取>>" + str);
            Logs.w("文件读取>>" + "<<大小>>" + i + "<<size>>" + size);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }
}

你可能感兴趣的:(简单的网络数据用文件来缓存)