티스토리 뷰

안녕하세요 박스여우입니다.

오늘은 안드로이드 에서 Cache를 사용하는 방법에 대해 알아보겠습니다.


캐시(Cache) 란?

캐시는 웹브라우저의 쿠키와 비슷한 느낌으로 데이터를 임시로 저장해 두는 장소를 말합니다. 앱을 만들어 서비스를 할 때 접속정보나 아이디 기억 등과 같은 굳이 서버에 저장할 필요가 없거나 서버에 저장하기 어려운 정보나 데이터들을 해결하기 위해 사용자의 기기에 저장해야 하는데, 이를 위해 READ,WRITE_EXTERNAL_STORAGE 퍼미션을 받아서 파일을 다루기는 좀 그렇고 해서! 저는 이를 캐시를 통해 해결했습니다. 캐시는 스토리지 접근 읽기 쓰기 퍼미션을 받지 않아도 파일을 다룰 수 있습니다.


 캐시(Cache) 사용하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Cache {
    Context context;
    public Cache(Context co){
        context = co;
    }
 
    public File getCacheDir(Context context) {
        File cacheDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(Environment.getExternalStorageDirectory(), "cachefolder");
            if(!cacheDir.isDirectory()) {
                cacheDir.mkdirs();
            }
        }
        if(!cacheDir.isDirectory()) {
            cacheDir = context.getCacheDir();
        }
        return cacheDir;
    }
 
    public void Write(String obj) throws IOException {
        File cacheDir = getCacheDir(context);
        File cacheFile = new File(cacheDir, "Cache.txt");
        if(!cacheFile.exists())cacheFile.createNewFile();
        FileWriter fileWriter = new FileWriter(cacheFile);
        fileWriter.write(obj);
        fileWriter.flush();
        fileWriter.close();
    }
 
    public String Read() throws IOException {
        File cacheDir = getCacheDir(context);
        File cacheFile = new File(cacheDir, "Cache.txt");
        if(!cacheFile.exists())cacheFile.createNewFile();
        FileInputStream inputStream = new FileInputStream(cacheFile);
        Scanner s = new Scanner(inputStream);
        String text="";
        while(s.hasNext()){
            text+=s.nextLine();
        }
        inputStream.close();
        return text;
    }
 
}
 
 
cs

getCacheFolder 메소드로 다루고 싶은 캐시 파일들을 생성할 수 있는 디렉토리를 얻어옵니다. 위의 코드를 잘 살펴보면 사용방법은 아실 수 있을 것 이라 생각합니다.


댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함