IT_Programming/Java

[Java] 메모리에 zip 파일 생성하기 / 파일 캐싱

JJun ™ 2010. 12. 29. 15:21

-------------------------------------------------------------------------------------------------

출처: http://tripoverit.blogspot.com/2008/04/java-create-zip-file-in-memory.html

-------------------------------------------------------------------------------------------------

 

/* 메모리에 zip 파일 생성하기 */

private static byte[] createZip(Map files) throws IOException


    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    ZipOutputStream zipfile = new ZipOutputStream(bos); 
   

    Iterator i = files.keySet().iterator(); 
    String fileName = null; 
    ZipEntry zipentry = null; 


    while (i.hasNext()) { 
        fileName = (String) i.next(); 
        zipentry = new ZipEntry(fileName); 
        zipfile.putNextEntry(zipentry); 
        zipfile.write((byte[]) files.get(fileName)); 
    } 


    zipfile.close(); 


    return bos.toByteArray(); 
}

 

 

-------------------------------------------------------------------------------------------------

출처: http://ncanis.tistory.com/104

-------------------------------------------------------------------------------------------------

 

package test;

 

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

 

public class Caching

{
    private long lastModified = 0L;
    private String value = null;
   
    // 키에 대한 value값을 가져온다.
    public String get(String key) throws IOException

    {
        URL url = this.getClass().getResource("/test/test.properties");
        File file = new File(url.getPath());
        // 파일이 수정되지 않았으면 기존에 로드된 정보를 리턴한다.
        if(file.lastModified()!=this.lastModified) {
            this.lastModified = file.lastModified();
            this.value = load(url,key);
        }
        return value;           
    }


    // test.properties 파일을 읽어 키의 value값을 읽어온다.
    public String load(URL url,String key) throws IOException

    {
        System.out.println("== 파일로부터 데이터 리로딩 ==");
        Properties p = new Properties();
        p.load(url.openStream());
        return p.getProperty(key);       
    }

    public static void main(String[] args) throws IOException {
        Caching c = new Caching();
        // 첫요청시에만 파일을 읽고, 나머지는 기존 정보를 가져오죠.~
        System.out.println("데이터로딩1 = "+c.get("message"));
        System.out.println("데이터로딩2 = "+c.get("message"));
        System.out.println("데이터로딩3 = "+c.get("message"));

    }

}

 

그저 파일이 변경됬는지만 확인하고,

변경이 됐으면 → 다시 로딩해 메모리에 올리고,
변경이 안됐으면 → 기존에 저장해놓은 정보를 리턴하는 예제