안드로이드 앱 개발 일지, 3차

안드로이드 앱 개발기 3

파일 입출력

수집된 데이터를 저장할 경우, 파일에 저장하면 된다. 전에 누가 개발한 코드를 보니 쉽게 사용하던데, android developer에서 보니 설명이 어렵게 되어 있다. stack overflow에서 찾아, 되는 코드를 만들 수 있었다.

android developer에는 internal storage는 아무 제한이 없이 사용하는데, 코드로 만들면 permission 문제인지 파일과 폴더를 만들 수 없다. internal storage의 기본 위치는 /data/…인데, 안드로이드에서 직접 만들어보니 안되었다. 갤럭시 노트2의 경우 권한으로 막아놓은 듯 하다. 이런 설명이 없으니, 하루 삽질을 하게 되었다.

결국 외부 저장소로 만들기로 했다. sd카드 슬롯이 없는데도 외부 저장소로 저장이 되었다. 꼭 sd카드일 필요는 없어 보인다. stack overflow에 있는 내용을 요약하면..
First, get a file object

You’ll need the storage path. For the internal storage, use:

File path = context.getFilesDir();

For the external storage (SD card), use:

File path = context.getExternalFilesDir(null);

위 부분을 아래와 같이 사용하면 앱별 폴더 이름을 특성화 할 수 있다.

 File directory = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "GapnFlush");
            if (!directory.mkdirs()) {
                Log.d("file", "Directory was created");
            }

이렇게 하면 갤럭시 노트의 경우,
/storage/emulated/0/Android/data/app이름/files/Documents에 GapnFlush란 폴더를 만든다.

Then create your file object:

File file = new File(path, "my-file-name.txt");

Write a string to the file

FileOutputStream stream = new FileOutputStream(file);
try {
    stream.write("text-to-write".getBytes());
} finally {
    stream.close();
}

Or with Google Guava

Files.write("text-to-write", file, "UTF-8");

앱 실행 전 권한도 설정을 해줘야 된다.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

이제 파일은 저장이 되니까, 입맛대로 쓰면 된다..

코멘트

댓글 남기기

이 사이트는 Akismet을 사용하여 스팸을 줄입니다. 댓글 데이터가 어떻게 처리되는지 알아보세요.