티스토리 뷰

Computer/Android

Android File 입출력

jamezc 2013. 12. 11. 11:30

==================   MainActivity.java   ==================


package com.example.filesaveloadexample;


import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;


import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.inputmethod.InputMethodManager;

import android.widget.EditText;

import android.widget.Toast;


public class MainActivity extends Activity {

/** Called when the activity is first created. */

EditText text, result;

// 키보드 보이고 숨기게 하기 위한 객체

InputMethodManager iManager;


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// EditText 연결하기

text = (EditText) findViewById(R.id.editText);

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

// 객체의 참조값 얻어오기

iManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);


}


// 버튼을 눌렀을 때 실행되는 콜백 메소드

public void push(View v) {

switch (v.getId()) {

case R.id.saveBtn: // 저장 버튼을 눌렀을 때

// text 객체에 입력한 문자열을 읽어온다

String msg = text.getText().toString();

// 키보드 숨기기

iManager.hideSoftInputFromWindow(text.getWindowToken(), 0);


/*

* 특정 editText 객체에 포커스 주면서 키보드 보이게 하기

* iManager.showSoftInput(editText, 0);

*/


// 파일에 저장하는 작업을 한다.

try {

// 파일을 출력하기 위해서 스트림 객체를 얻어온다.(파일이름, 파일접근권한)

// openFileOutput는 activity의 메소드이다.

FileOutputStream fos = openFileOutput("myText.txt",

Context.MODE_WORLD_WRITEABLE);

// 문자열을 바이트 단위로 변환해서 얻어온다.

byte[] strByte = msg.getBytes();

// 스트림을 이용해서 파일에 기록한다.

fos.write(strByte);

// close해주어야 파일이 생성된다.

fos.close();

Toast.makeText(MainActivity.this, "파일 저장 성공", 0).show();

} catch (IOException e) {

Toast.makeText(MainActivity.this, "파일 저장 실패", 0).show();

Log.e("파일저장 에러메세지:", e.getMessage());

}

text.setText("");

break;

case R.id.load: // 읽어오기 버튼을 눌렀을때

try {

// 파일에서 읽어오기 위한 스트림 객체 얻어오기

FileInputStream fis = openFileInput("myText.txt");

// 바이트 단위로 읽어오기 위한 배열 준디

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

// byte 배열을 문자열로 변환한다.

String readedStr = new String(buffer);

// 읽어온 문장을 출력하기

result.setText(readedStr);

} catch (IOException e) {

Log.e("파일 읽어오기 실패:", e.getMessage());

}


break;


case R.id.delete: // 삭제버튼을 눌렀을 경우

// 파일삭제하기

boolean isDeleted = deleteFile("myText.txt");

if (isDeleted) {

Toast.makeText(MainActivity.this, "파일 삭제 성공", 0).show();

} else {

Toast.makeText(MainActivity.this, "파일 삭제 실패", 0).show();

}

break;

// 리소스는 res/raw폴더에 추가된 텍스트 형식의 파일로부터 읽어오는 것을 뜻한다.

case R.id.loadRes: // 리소스 버튼을 눌렀을때

// 리소스에서읽어오기 위한 스트링 객체 얻어오기

InputStream is = getResources().openRawResource(R.raw.test);

try {

// 바이트 단위로 읽어오기

byte[] buffer = new byte[is.available()];

is.read(buffer);

is.close();

// 읽어온 바이트 배열을 문자열로 변환하기

String str = new String(buffer);

result.setText(str);

} catch (IOException e) {

Log.e("리소스 로딩 실패:", e.getMessage());

}

break;

}// switch


}// push()

}






=================   activity_main.xml   =================


<?xml version="1.0" encoding="utf-8"?>

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

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

 <TextView  

    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="파일 입출력 예제"

    />

    <EditText 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:id="@+id/editText"

    android:hint="저장할 메모를 입력하세요"

    />

    <LinearLayout 

    android:layout_height="wrap_content"

    android:layout_width="fill_parent"

    >

     <Button android:layout_width="0dp"

     android:layout_height="wrap_content"

  android:layout_weight="1"

  android:text="저장" 

  android:id="@+id/saveBtn"

  android:onClick="push"   

  />

  <Button android:layout_width="0dp"

     android:layout_height="wrap_content"

  android:layout_weight="1"

  android:text="읽어오기" 

  android:id="@+id/load"

  android:onClick="push"   

  />

  <Button android:layout_width="0dp"

     android:layout_height="wrap_content"

  android:layout_weight="1"

  android:text="삭제하기" 

  android:id="@+id/delete"

  android:onClick="push"   

  />

  <Button android:layout_width="0dp"

     android:layout_height="wrap_content"

  android:layout_weight="1"

  android:text="리소스" 

  android:id="@+id/loadRes"

  android:onClick="push"   

  />

    </LinearLayout>

    <EditText 

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:editable="false"

    android:hint="읽어온 문자열"

    android:id="@+id/result"

    />

</LinearLayout>



댓글

파트너스 활동을 통해 일정액의 수수료를 제공받을 수 있음



Total
Today
Yesterday
최근에 달린 댓글