프로그램안에서 사용해야 할 다량의 문자열들을 정의하는데 있어서 효율적인 방법은 소스코드에 모든 내용을 포함시키기 보다는 외부에 내용을 저장해 놓고 필요할 때 마다 읽어오는 방법입니다.
안드로이드에서는 문자열로서 사용하기 위한 데이터를 보관하기 위한 기법으로 리소스 XML에 내용을 기술하는 방법과 SQLite를 사용하는 방법, 그리고 assets 디렉토리를 사용하는 방법을 제공해 주고 있습니다.
오늘 소개할 내용은 assets 디렉토리에 저장된 텍스트 파일을 프로그램내로 읽어들이는 내용입니다.
assets 디렉토리
안드로이드 프로젝트를 이클립스 상에서 보면 assets라는 (평소에는 잘 사용하지 않는) 디렉토리에 있습니다. 프로그램과 직접적으로 연관되지 않은 비 리소스 파일들을 저장해 놓고 필요한 경우 스트림을 생성하여 읽어들이기 위한 저장공간입니다.
이 폴더안에 test.txt라는 파일을 넣었다고 가정하고 이 파일의 내용을 프로그램의 Runtime시에 읽어오는 방법을 소개하겠습니다.
AssetManager의 객체 생성
Context 클래스 내에 보면 getResource()라는 메소드가 있습니다. getResource()라는 메소드는 Resources 라는 클래스의 객체를 리턴합니다. 이 객체는 App이 갖고 있는 자원에 접근할 수 있는 객체입니다. 이 객체를 통해서 AssetManager라는 객체를 얻을 수 있습니다.
<strong>Context 클래스</strong>
<strong>Resources getResource();</strong><br />리소스 객체를 얻어옵니다.
만약 Activity안에서 AssetManager객체를 얻고자 한다면 다음과 같이 사용할 수 있습니다.
Resources r = getResource();
Context 클래스는 Activity 클래스의 상위 클래스이기 때문에 Activity 안에서는 Context클래스 내의 기능들을 자기것인양 사용할 수 있습니다.
리소스 객체를 얻은 후에는 이 리소스 객체를 통해서 AssetManager 객체를 얻어옵니다.
<strong>Resources클래스</strong>
<strong>AssetManager getAssets();</strong><br />AssetManager 객체를 얻어옵니다.
AssetManager를 통하여 파일 열기
AssetManager 객체가 생성되면 이 객체의 open() 메소드를 사용하여 InputStream 객체를 얻을 수 있습니다. open() 메소드는 호출 시에 대상 파일의 이름을 문자열로 전달합니다. 파일이 위치한 경로는 이클립스 프로젝트 내의 assets 라는 폴더로 이미 확정이 되어 있는 상태이기 때문에 전달하는 파라미터는 파일의 이름만을 전달합니다. 주의하실 점은 이 메소드를 사용하려면 try { } ~ catch { } 블록으로 묶어 주어야 한다는 점 입니다. 그래서 Asset객체를 통해서 InputStream을 여는 과정은 다음과 같아집니다.
- AssetManager am = m_context.getResources().getAssets();
- InputStream is = null;
-
- try {
- is = am.open("contact.txt");
-
- } catch (Exception e) {
-
- } finally {
- if (is != null) {
- try {
- is.close();
- is = null;
- } catch (Exception e) {}
- }
- }
-
- am = null;
AssetManager am = m_context.getResources().getAssets();
InputStream is = null;
try {
is = am.open("contact.txt");
// 스트림을 사용합니다.
} catch (Exception e) {
// 에러가 발생한 경우의 처리
} finally {
if (is != null) {
try {
is.close();
is = null;
} catch (Exception e) {}
}
}
am = null;
test.txt 파일을 읽기
Context객체와 읽어야 할 파일이름을 전달하였을 때, 해당 파일의 내용을 읽어서 문자열로 리턴해 주는 함수를 구현해 본다면 다음과 같이 구현할 수 있겠습니다.
- String readAsset(Context context, String file_name) {
- AssetManager am = context.getResources().getAssets();
- InputStream is = null;
-
- String result = null;
-
- try {
- is = am.open(file_name);
- int size = is.available();
-
- if (size > 0) {
- byte[] data = new byte[size];
- is.read(data);
- result = new String(data);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (is != null) {
- try {
- is.close();
- is = null;
- } catch (Exception e) {}
- }
- }
-
- am = null;
- return result;
- }
String readAsset(Context context, String file_name) {
AssetManager am = context.getResources().getAssets();
InputStream is = null;
// 읽어들인 문자열이 담길 변수
String result = null;
try {
is = am.open(file_name);
int size = is.available();
if (size > 0) {
byte[] data = new byte[size];
is.read(data);
result = new String(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
is = null;
} catch (Exception e) {}
}
}
am = null;
return result;
}
Activity클래스 안에서 사용방법은 다음과 같습니다.
String data = readAsset(this, "test.txt");