레이블이 file caching인 게시물을 표시합니다. 모든 게시물 표시
레이블이 file caching인 게시물을 표시합니다. 모든 게시물 표시

2012-10-14

Java] Java 파일 캐싱




출처 : http://www.ezslookingaround.com/blog/tech/?no=1414&category=


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



Java - Create Zip file in memory


 

I find myself writing and rewriting this piece of code whenever I want to zip a set of files (in memory) and return the zipped file back as an object in memory. I often use this when the user requests a download of multiple reports and the deployment environment doesn't allow for disk access.

I thought I'd post it here so that I could copy-paste it the next time I need it :) If you've stumbled upon this page, you're free to use the code below too!
  1. privatestaticbyte[] createZip(Map files) throws IOException {  
  2.     ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  3.     ZipOutputStream zipfile = new ZipOutputStream(bos);  
  4.     Iterator i = files.keySet().iterator();  
  5.     String fileName = null;  
  6.     ZipEntry zipentry = null;  
  7.     while (i.hasNext()) {  
  8.         fileName = (String) i.next();  
  9.         zipentry = new ZipEntry(fileName);  
  10.         zipfile.putNextEntry(zipentry);  
  11.         zipfile.write((byte[]) files.get(fileName));  
  12.     }  
  13.     zipfile.close();  
  14.     return bos.toByteArray();  


Java 로 간단한 파일 캐싱을. ^^

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

File Caching.
오늘의 2번째 글입니다.~ ^^

간단한 파일캐싱에 대하여 한번 써봤습니다.
별로 팁이란것도 아니지만 심심해서. ㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎ

보통 어떤 flag나 환경설정 정보를 파일에 저장할때가 있습니다.
예를 들어, database url 이나, 로그인 정보, 아니면 구현 클래스 이름 등등.
자주바뀌어야 하는 정보들 말이죠 :)

자주 바뀌어야 하는 정보라면 로더 클래스가 이 환경설정 파일을 읽어 시스템에 적용하는게 보통이죠.
그렇게 하면 파일내의 정보가 바뀌더라도 재 컴파일을 안해도 되는 장점이 있습니다.

근데,
만약 항상 파일내의 데이터를 가져오는 부분에 복잡한 루틴이 걸려있으면 어떨까요.
시스템의 성능은 많이 떨어지게 됩니다.

워, 파일 내용이 바뀌지도 않았는데 계속 파일을 읽어서 확인하다죠 ㅡ.ㅡ;

이럴때는 파일 캐싱을 통해 가져오면 되지요.

평소에는 파일내용을 메모리에 올려놓다가,
파일 내용이 바뀌었다면 다시 로딩해서 메모리에 올려놓으면 됩니다.

ps. 대부분의 개발자분들은 잘하시만, 가끔가다보면 요청함수에, 파일로딩 해서 정보를 분석하는 로직을 그냥 넣어놓는것도 심심찮게 보게 된답니다.~ -0-


아래는 파일 캐싱 예제 소스 입니다.
구현은 간단합니다. 그저 파일이 변경됬는지만 확인하고,
변경이 됐으면 => 다시 로딩해 메모리에 올리고,
변경이 안됐으면 => 기존에 저장해놓은 정보를 리턴하는거죠.~~
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"));

    }

}

소스는 더럽지만 대충 개념은 나왔네용. ㅎㅎ
근데 한가지 주의 할 게 있습니다.
이런 설정정보를 File로 빼는것에 대한 주의점이.~
왜 몇년동안 바뀌지도 정보를 파일로 빼는지,
간단한 정보일 뿐인데 멋있다고(?) xml  로 설정정보를 만들어, 무거운 Parser를 돌리는 것인지. ㅡ.ㅡ;
이런거는 조심해야겠습니다.

무엇이든지 해당 프로젝트와 로직에 맞는 방법을 찾아 적용하는게 가장 중요하겠죠. :)
test.properties 내용.
message=ver_1.01