a simple cache for android and java

Related tags

Utility ASimpleCache
Overview

ASimpleCache


ASimpleCache 是一个为android制定的 轻量级的 开源缓存框架。轻量到只有一个java文件(由十几个类精简而来)。


1、它可以缓存什么东西?

普通的字符串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java对象,和 byte数据。

2、它有什么特色?

  • 特色主要是:
  • 1:轻,轻到只有一个JAVA文件。
  • 2:可配置,可以配置缓存路径,缓存大小,缓存数量等。
  • 3:可以设置缓存超时时间,缓存超时自动失效,并被删除。
  • 4:支持多进程。

##3、它在android中可以用在哪些场景?

  • 1、替换SharePreference当做配置文件
  • 2、可以缓存网络请求数据,比如oschina的android客户端可以缓存http请求的新闻内容,缓存时间假设为1个小时,超时后自动失效,让客户端重新请求新的数据,减少客户端流量,同时减少服务器并发量。
  • 3、您来说...

##4、如何使用 ASimpleCache? 以下有个小的demo,希望您能喜欢:

ACache mCache = ACache.get(this);
mCache.put("test_key1", "test value");
mCache.put("test_key2", "test value", 10);//保存10秒,如果超过10秒去获取这个key,将为null
mCache.put("test_key3", "test value", 2 * ACache.TIME_DAY);//保存两天,如果超过两天去获取这个key,将为null

获取数据

ACache mCache = ACache.get(this);
String value = mCache.getAsString("test_key1");

更多示例请见Demo

#关于作者michael

  • 屌丝程序员一枚,喜欢开源。
  • 个人博客:http://www.yangfuhai.com
  • 交流QQ群 : 192341294(已满) 246710918(未满)
Comments
  • Suggestion for the project.

    Suggestion for the project.

    I like how the project was created but did not understand why this:

            public void put(String key, byte[] value) {
                    File file = mCache.newFile(key);
                    FileOutputStream out = null;
                    try {
                            out = new FileOutputStream(file);
                            out.write(value);
                    } catch (Exception e) {
                            e.printStackTrace();
                    } finally {
                            if (out != null) {
                                    try {
                                            out.flush();
                                            out.close();
                                    } catch (IOException e) {
                                            e.printStackTrace();
                                    }
                            }
                            mCache.put(file);
                    }
            }
    

    When the api cache provides the ability to save in the cache based on File:

    private void put(File file)

    Faced with this situation, I suggest (what I currently need) that create a method that works with File(public):

    public void put(File file)

    So I could add a File in Cache, more record (when necessary), using a FileInputStream. Would look like this:

     File mFile = new File("test.txt");
    
     ACache mCache = ACache.get(this);
     mCache.put("myFileKey", mFile);
    
     FileOutputStream out = new FileOutputStream(mFile);
     out.write("my bytes".getBytes());
    

    The need then arose to write because I need to save content from the internet (save a cache of bytes in memory is not an option).

    opened by alexsilva 1
  • Adding support gradle used by Android Studio (Beta) 0.8.7.

    Adding support gradle used by Android Studio (Beta) 0.8.7.

    The 'gradle' file will import the project as a module into the idle android studio. This will facilitate the use of the project (its addition) in the development environment.

    opened by alexsilva 0
  • Implementing support Input / Output / Streams.

    Implementing support Input / Output / Streams.

    As the ability to work with various file cache was necessary for me, I added this functionality, create the model example and I hope your review and incorporation of my work.

     ACache cache = new ACache(this);
     try {
         // creating cache
    
         OutputStream ostream = cache.put("myFileName");
         ostream.write("some bytes".getBytes());
    
         // now update cache!
         ostream.close();
    
         // open cache
    
         InputStream stream = cache.get("myFileName");
         stream.close();
    
     } catch(FileNotFoundException e){
          e.printStackTrace()
     }
    
    opened by alexsilva 0
  • 极少数情况下会出现NumberFormatException

    极少数情况下会出现NumberFormatException

    昨天发现NumberFormatException这个异常,定位到判断时候过期的判断,但是缓存的数据并没有设置过期时间,但是刚好缓存的数据包含‘-’,查看那一段代码,是截取前13位字符,判断是不是时间的,然后转化为时间的,所以这里会有一个问题就是,极少数情况下,刚好string中包含,“-”,有同时满足后面有一个“ ”空格,就满足indexOf(data, mSeparator),这一个string就会被错认为一个包含过期时间的字段,然后转化时间就会报错,所以过期时间的判断有点不严谨,会有这种情况的出现,虽然很少很少,建议转化加一个try catch,可以解决

    opened by hi-lay 1
  • 代码优化建议

    代码优化建议

    `

    //private static Map<String, ACache> mInstanceMap = Collections.synchronizedMap(new HashMap<String, ACache>()); private static ACache instance = null;

    /**
     * 个人觉得没必要用map来缓存实例,一个就够用了
     * @param cacheDir
     * @param max_zise
     * @param max_count
     * @return
     */
    public  static ACache get(File cacheDir, long max_zise, int max_count) {
        if (instance == null) {
            synchronized (ACache.class) {
                //ACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid());
                if (instance == null) {
                    instance = new ACache(cacheDir, max_zise, max_count);
                    //mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);
                }
            }
        }
        return instance;
    }
    

        /**
         * hashCode发生碰撞怎么办,我建议用base64
         * @param key
         * @return
         */
        private File newFile(String key) {
            //return new File(cacheDir, key.hashCode() + "");
            return new File(cacheDir, Base64.encodeToString(key.getBytes(), Base64.NO_WRAP) + "");
        }
    

    ` 我改过的版本在这里: https://github.com/moz1q1/WalleLibrary/tree/master/library_utils/src/main/java/org/wall/mo/utils/cache 你都不合并人家代码,我只能这样改了

    opened by mosentest 1
  • 部分机型可能无法创建缓存目录,抛出的异常导致程序crash,能否对这一场景做处理

    部分机型可能无法创建缓存目录,抛出的异常导致程序crash,能否对这一场景做处理

    private ACache(File cacheDir, long max_size, int max_count) { if (!cacheDir.exists() && !cacheDir.mkdirs()) { throw new RuntimeException("can't make dirs in " + cacheDir.getAbsolutePath()); } } 主要是一段代码

    opened by clouse 9
Owner
Michael Yang
wechat:wx198819880
Michael Yang
DiskCache - Simple and readable disk cache for kotlin and android applications

DiskCache Simple and readable disk cache for kotlin and android applications (with journaled lru strategy) This is a simple lru disk cache, based on t

Giovanni Corte 14 Dec 2, 2022
A simple Android utils library to write any type of data into cache files and read them later.

CacheUtilsLibrary This is a simple Android utils library to write any type of data into cache files and then read them later, using Gson to serialize

Wesley Lin 134 Nov 25, 2022
Expirable Disk Lru Cache is a secure(with encryption) wrapper for [DiskLruCache](https://github.com/JakeWharton/DiskLruCache) that allows expiring of key/value pairs by specifying evictionTimeSpan. It has very simple API.

ExpirableDiskLruCache ExpirableDiskLruCache is a wrapper for DiskLruCache that allows expiring of key/value pairs by specifying evictionTimeSpan. It h

Vijay Rawat 24 Oct 3, 2022
Android library to easily serialize and cache your objects to disk using key/value pairs.

Deprecated This project is no longer maintained. No new issues or pull requests will be accepted. You can still use the source or fork the project to

Anup Cowkur 667 Dec 22, 2022
General purpose utilities and hash functions for Android and Java (aka java-common)

Essentials Essentials are a collection of general-purpose classes we found useful in many occasions. Beats standard Java API performance, e.g. LongHas

Markus Junginger 1.4k Dec 29, 2022
General purpose utilities and hash functions for Android and Java (aka java-common)

Essentials Essentials are a collection of general-purpose classes we found useful in many occasions. Beats standard Java API performance, e.g. LongHas

Markus Junginger 1.4k Dec 29, 2022
WebSocket & WAMP in Java for Android and Java 8

Autobahn|Java Client library providing WAMP on Java 8 (Netty) and Android, plus (secure) WebSocket for Android. Autobahn|Java is a subproject of the A

Crossbar.io 1.5k Dec 9, 2022
WebSocket & WAMP in Java for Android and Java 8

Autobahn|Java Client library providing WAMP on Java 8 (Netty) and Android, plus (secure) WebSocket for Android. Autobahn|Java is a subproject of the A

Crossbar.io 1.5k Dec 9, 2022
Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platform the code is running.

Trail Trail is a simple logging system for Java and Android. Create logs using the same API and the library will detect automatically in which platfor

Mauricio Togneri 13 Aug 29, 2022
gRPC and protocol buffers for Android, Kotlin, and Java.

Wire “A man got to have a code!” - Omar Little See the project website for documentation and APIs. As our teams and programs grow, the variety and vol

Square 3.9k Dec 31, 2022
A lightning fast, transactional, file-based FIFO for Android and Java.

Tape by Square, Inc. Tape is a collection of queue-related classes for Android and Java. QueueFile is a lightning-fast, transactional, file-based FIFO

Square 2.4k Dec 30, 2022
UPnP/DLNA library for Java and Android

Cling EOL: This project is no longer actively maintained, code may be outdated. If you are interested in maintaining and developing this project, comm

4th Line 1.6k Jan 4, 2023
Error handling library for Android and Java

ErrorHandler Error handling library for Android and Java Encapsulate error handling logic into objects that adhere to configurable defaults. Then pass

null 237 Dec 29, 2022
Multiplaform kotlin library for calculating text differences. Based on java-diff-utils, supports JVM, JS and native targets.

kotlin-multiplatform-diff This is a port of java-diff-utils to kotlin with multiplatform support. All credit for the implementation goes to original a

Peter Trifanov 51 Jan 3, 2023
BinGait is a tool to disassemble and view java class files, developed by BinClub.

BinGait Tool to diassemble java class files created by x4e. Usage To run BinGait, run java -jar target/bingait-shadow.jar and BinGait will launch. If

null 18 Jul 7, 2022
A low intrusive, configurable android library that converts layout XML files into Java code to improve performance

qxml English 一个低侵入,可配置的 Android 库,用于将 layout xml 文件转换为 Java 代码以提高性能。 与X2C的对比 X2C: 使用注解处理器生成View类,使用时需要在类中添加注解,并替换setContentView方法,侵入性较强; 对于布局属性的支持不够完美

null 74 Oct 6, 2022
Runtime code generation for the Java virtual machine.

Byte Buddy runtime code generation for the Java virtual machine Byte Buddy is a code generation and manipulation library for creating and modifying Ja

Rafael Winterhalter 5.3k Jan 7, 2023
Apk parser for java

APK parser lib, for decoding binary XML files, getting APK meta info. Table of Contents Features Get APK-parser Usage 1. APK Info 2. Get Binary XML an

Hsiafan 1.1k Jan 2, 2023
Apk parser for java

APK parser lib, for decoding binary XML files, getting APK meta info. Table of Contents Features Get APK-parser Usage 1. APK Info 2. Get Binary XML an

Hsiafan 1.1k Dec 18, 2022