缓存的一种实现

在实际项目中,需要从网络请求资源,然后显示出来,而且从网络请求资源再很多情况下是重复请求的情况。比方说在一个音乐点播系统,音乐本身使用缓存,文件略大。关于音乐的说明信息:专辑海报,歌手信息等。这些信息固有稳定性,适合使用缓存。具体实现思路如下:

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.InputStream;

public class FileInput {
    private static String path = "/mnt/sdcard/catch/";
    private static String server ="http://192.168.132.103:8008/";
    
    public static String getResourcePath(String fileName,String type,String id){
    	URL url = null;
    	InputStream in =null;
    	FileOutputStream out = null;
    	//首先不访问网络,先从缓存的目录下查找,如果找不到在从网络上访问。然后并存到本地。
    	File tempFile = new File(path+fileName);
    	
    	if(!tempFile.exists()){
    	 try {
    		tempFile.createNewFile();
    		url = new URL(server+type+"/id/"+fileName);
			in = url.openStream();
			out = new FileOutputStream(new File(path+fileName));
			byte[]  buffer = new byte[1024];
			int readByte =0;
			while((readByte = in.read(buffer))>0){
				out.write(readByte);
				out.flush();
			}
		
		} catch (MalformedURLException e) {			
			e.printStackTrace();
		} catch (IOException e) {			
			e.printStackTrace();
		}finally{			
				try {
					if(in!=null)
						in.close();
				    if(out!=null)
				    	out.close();
				} catch (IOException e) {					
					e.printStackTrace();
				}
		}
      }    	
    	
    	return path+fileName;
    }
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值