반응형

EditText 에 입력한 글씨를 외부 메모리(Internal Storage) 즉, SDcard에 저장하고 다시 읽어오는 소스입니다.


먼저, 여러분의 테스터 단말기(실제 스마트폰 또는 에뮬레이터)에 SDcard가 있는지 확인하시기 바랍니다.




메인화면                                        SDcard에 저장                               SDcard에서 읽어오기

          


Layout 파일

 activity_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">

    

    <EditText android:id="@+id/edit"

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:padding="5dp"

        android:inputType="text"

        android:hint="input text"/>

    

    <Button android:id="@+id/btn_save"

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:text="save file into External(SDcard)"

        android:onClick="mOnClick"/>

    

    <Button android:id="@+id/btn_load"

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:text="load file from External(SDcard)"

        android:onClick="mOnClick"/>

    

    <TextView android:id="@+id/text"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:padding="5dp"

        android:text="Show data from file"/>


</LinearLayout>



소스파일

 

 MainActivity.java

 public class MainActivity extends Activity {

EditText edit;

TextView text;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

edit= (EditText)findViewById(R.id.edit);

text= (TextView)findViewById(R.id.text); 

}

//Button을 클릭했을 때 자동으로 호출되는 callback method....

public void mOnClick(View v){

String state= Environment.getExternalStorageState(); //외부저장소(SDcard)의 상태 얻어오기

File path;    //저장 데이터가 존재하는 디렉토리경로

File file;     //파일명까지 포함한 경로

switch(v.getId()){

case R.id.btn_save:  //External Storage(SDcard)에 file 저장하기

if(!state.equals(Environment.MEDIA_MOUNTED)){ // SDcard 의 상태가 쓰기 가능한 상태로 마운트되었는지 확인

Toast.makeText(this, "SDcard Not Mounted", Toast.LENGTH_SHORT).show();

return;

}

String data= edit.getText().toString();  //EditText의 Text 얻어오기

//SDcard에 데이터 종류(Type)에 따라 자동으로 분류된 저장 폴더 경로선택

//Environment.DIRECTORY_DOWNLOADS : 사용자에의해 다운로드가 된 파일들이 놓여지는 표준 저장소

path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

file= new File(path, "Data.txt"); //파일명까지 포함함 경로의 File 객체 생성

try {

//데이터 추가가 가능한 파일 작성자(FileWriter 객체생성)

FileWriter wr= new FileWriter(file,true); //두번째 파라미터 true: 기존파일에 추가할지 여부를 나타냅니다.

PrintWriter writer= new PrintWriter(wr); 

writer.println(data);

writer.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

//소프트 키보드 없애기

InputMethodManager imm= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

break;

case R.id.btn_load:  //External Storage(SDcard)에서 file 읽어오기

// SDcard 의 상태가 읽기/쓰기가 가능하거나 또는 읽기만 가능한 상태로 마운트되었는지 확인

if( !(state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) ){

Toast.makeText(this, "SDcard Not Mounted", Toast.LENGTH_SHORT).show();

return;

}

StringBuffer buffer= new StringBuffer();

path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

file= new File(path, "Data.txt");

try {

FileReader in= new FileReader(file);

BufferedReader reader= new BufferedReader(in);

String str= reader.readLine();

while( str!=null ){

buffer.append(str+"\n");

str= reader.readLine();//한 줄씩 읽어오기

}

text.setText(buffer.toString());

reader.close();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

break;

}

}

}

 



 외부 저장소를 사용하기 위해서는 사용 권한(uses-permission)이 필요합니다.

여러분 프로젝트의 메니페스트 파일에 퍼미션을 추가합니다.


 AndroidManifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.kitesoft.externalstorage"

    android:versionCode="1"

    android:versionName="1.0" >


    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="19" />

    

    <!-- 외부저장소(SDcard) 사용허가 요청  -->

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


    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name=".MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>


</manifest>






저장된 위치 확인

(Eclipse 에서 DDMS의 mnt/sdcard/Download/)

- 외부 메모리(SDcard)에 위치해 있기 때문에 앱을 제거해도 파일은 여전히 남아있게 됩니다.





Tip. 사용자가 원하는 디렉토리에 저장하기

 기본 SDcard의 디렉토리가 아닌 사용자가 원하는 디렉토리를 사용하고 싶다면 아래 코드로 디렉토리 pah를 만드시면 됩니다.

 //SDcard의 절대 경로 얻어오기( /mnt/sdcard )

 String absolutePath= Environment.getExternalStorageDirectory().getAbsolutePath();

 // 커스텀 디렉토리로서 "/custDir" 디렉토리 추가  ( /mnt/sdcard/custDir/ )

 String newPath= absolutePath+"/custDir";

 File path= new File(newPath); //새로운 디렉토리로 File 객체 생성

 if( !path.exists() ) path.mkdir(); //만약 처음 디렉토리를 만들면 존재하지 않기때문에 디렉토리를 생성( make Directory )

  .......



사용자 정의 디렉토리 사용시 저장 위치( /mnt/sdcard/custDir/ )




























반응형

+ Recent posts