[Android] 속성파일을 앱에 포함시켜서 배포하기
자바파일에서 참고하는 속성파일을 txt로 저장해두고 그걸 읽어들여서 프로그램을 실행하고 싶었는데
그게 생각처럼 쉽게 되질 않았다.
DDMS 밑에 폴더를 만들어서 파일을 넣어놓고 쓰라는 사람도 있었는데,
이건 솔직히 좀 불편한 방법같고..
뭔가 쉬운게 있을것 같았는데
검색하다 맘에 드는 방법이 있어서 그대로 해보니 정말 간단히 풀렸다.
res/raw 밑에 소문자와 숫자로만 이루어진 파일명으로 파일을 생성해두고
그 파일의 위치는 R에서 자동으로 참조하므로
그 파일을 읽어서 사용하는것이다.
내가 읽어들이려고 만든 파일은 한 줄에 7개의 숫자들이 탭으로 분리되어 나열된 파일이다.
(예)
....
10 14 18 20 23 30 41
6 12 17 18 31 32 21
4 5 6 8 17 39 25
5 13 17 18 33 42 44
7 8 27 29 36 43 6
2 4 21 26 43 44 16
4 5 7 18 20 25 31
...
이런식이다.
1. 읽어들일 파일에 대한 정보 담기
보통은 File이라는 객체를 생성해서 담아주는데
안드로이드에선 Activity 클래스 내에서 openRawResource 메소드와 R을 활용하는 방식으로 쓴다.
//File file = new File( "winningnumbers.txt"); InputStream is = getResources().openRawResource(R.raw.winningnumbers);
2. 파일에서 정보를 읽어들여 BufferedReader에 담기
보통은 생성된 파일 정보를 이용해서 BufferedReader로 만들어 읽어들이는데,
FileReader를 쓰는대신 위에서 생성된 InputStream객체를 이용해서 BufferedReader를 생성했다.
try { //BufferedReader br = new BufferedReader(new FileReader(file.getAbsoluteFile())); InputStreamReader isr = new InputStreamReader( is); BufferedReader br = new BufferedReader( isr); String line = ""; String tempArray[] = new String[7]; totalCount = 0; int tempInt = 0; while ((line = br.readLine()) != null) { totalCount += 1; tempArray = line.split("\t"); for ( int i = 0; i < 7; i++) { tempInt = Integer.parseInt(tempArray[ i ]) - 1; if ( numbers [ tempInt ][0] == tempInt + 1) { // setting count numbers [ tempInt ][1] += 1; } } } br.close(); } catch( FileNotFoundException fnfe) { fnfe.getStackTrace(); System.out.println( fnfe.getMessage()); } catch( IOException ie) { ie.getStackTrace(); } catch( Exception e) { System.out.println( e.getMessage()); }
처음에 res/raw 밑에 파일을 두는 방식을 몰랐을때는 계속 파일을 찾지못해
FileNotFoundException 으로 원하는 결과값이 나오지 않았었는데
지금은 잘 나온다. 히힛..
[참고]