앱 개발을 하면서 간단한 키값 정도의 데이터는 데이터베이스를 사용하기 보다는 파일에 저장해서 사용하는게 편한 경우가 있어 파일 쓰기 및 읽기 테스트를 해 봅니다만들어 보는 최종 모습은 좀 엉성하지만 button 하나와 textview 하나 입니다.


android file write read


1. 프로젝트 생성

 

먼저 간단하게 프로젝트를 하나 만들고


android file write read


Empty Activity를 선택 합니다.


android file write read


Name은 적당히 적어주고 package copycoding.tistory.filetest로 하였습니다.



layout은 아이템이 2개밖에 없으니 TextView는 기본으로 생성되는 Hello World를 사용하고 id만 추가해 주었고 버튼은 OnClick을 추가해서 함수를 바로 호출 하도록 했습니다.

 

<TextView

        android:id="@+id/fileContents"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello World!"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

 

    <Button

        android:id="@+id/button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginStart="76dp"

        android:layout_marginLeft="76dp"

        android:layout_marginTop="108dp"

        android:text="Button"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent"

        android:onClick="btnClick"/>

 

프로그램도 일반적인 java로 구현한 파일 읽기 쓰기와 비슷 합니다.

버튼을 클릭 하면 만들어 놓은 writeFile() 함수에 파일명과 데이터를 보내 파일에 쓰기를 하고 readFile()을 이용하여 입력된 내용을 읽어 옵니다그리고 읽어온 내용을 textView에 출력하는 내용 입니다.


public void btnClick(View view) {

try {

writeFile("testFile.txt", "testtttttttt");

            String rFile = readFile("testFile.txt");

            textView.setText(rFile);

        } catch (IOException e) {

            e.printStackTrace();

        }

}

 

writeFile() 함수는 전달받은 내용을 파일에 쓰기를 하고

OutputStreamWriter oStreamWriter = new OutputStreamWriter(openFileOutput(fileName,

                    Context.MODE_PRIVATE));

oStreamWriter.write(msg);

oStreamWriter.close();

 

readFile() 함수는 파일에서 내용을 읽어 옵니다.

InputStream iStream = openFileInput(fileName);

if(iStream != null) {

InputStreamReader iStreamReader = new InputStreamReader(iStream);

    BufferedReader bufferedReader = new BufferedReader(iStreamReader);

    String temp = "";

    StringBuffer sBuffer = new StringBuffer();

    while((temp = bufferedReader.readLine()) != null) {

         sBuffer.append(temp);

}

iStream.close();

fileContents = sBuffer.toString();

 

파일 읽기와 쓰기에 사용된 입출력 함수는 위에서 사용한 함수 이외에 FileInputStream, FileOutputStream 등 다른 함수를 이용해도 되고 본인이 알고 있는 함수를 사용하면 됩니다.

 

프로그램을 실행하고 BUTTON을 눌러서 결과를 확인 합니다.


android file write read



2. 생성 파일 확인

 

결과를 확인했으니 생성된 testFile.txt 파일도 확인해 봅니다파일 탐색기를 이용해 확인을 하려고 하면 파일을 제대로 확인 할 수 없습니다안드로이드 스튜디오에서 제공하는 Device File Explorer를 이용하면 쉽게 확인이 가능 합니다.

 

메뉴에서


View > Tool Windows > Device File Explorer


를 선택 하면 


android file write read


Android Studio 우측에 현재 연결된 핸드폰의 내용을 탐색할 수 있습니다.


android file write read


프로젝트와 관련된 파일들은 package 으로 폴더가 /data/data/ 아래 생성 되는데 현재 만든 프로젝트의 패키지가 copycoding.tistory.filetest 이니 좀더 아래에 생성되어 있겠네요. 스크롤을 아래로 내려서


android file write read


폴더가 생성되어 있으니 확장을 하고 msg를 저장한 testFile.txt 파일을 더블클릭해서 열어 봅니다.


android file write read

 

그러면 저장된 파일 내용을 확인할 수 있습니다.

 

 

3. 전체 소스


activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context=".MainActivity">

    <TextView
       
android:id="@+id/fileContents"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Hello World!"
       
app:layout_constraintBottom_toBottomOf="parent"
       
app:layout_constraintLeft_toLeftOf="parent"
       
app:layout_constraintRight_toRightOf="parent"
       
app:layout_constraintTop_toTopOf="parent" />

    <Button
       
android:id="@+id/button"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_marginStart="76dp"
       
android:layout_marginLeft="76dp"
       
android:layout_marginTop="108dp"
       
android:text="Button"
       
app:layout_constraintStart_toStartOf="parent"
       
app:layout_constraintTop_toTopOf="parent"
       
android:onClick="btnClick"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.java


package copycoding.tistory.filetest;
import
androidx.appcompat.app.AppCompatActivity;
import
android.content.Context;
import
android.os.Bundle;
import
android.view.View;
import
android.widget.TextView;
import
java.io.BufferedReader;
import
java.io.FileNotFoundException;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.io.OutputStreamWriter;

public class
MainActivity extends AppCompatActivity {
    TextView
textView;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
       
setContentView(R.layout.activity_main);
       
textView = (TextView) findViewById(R.id.fileContents);
   
}
   
private void writeFile(String fileName, String msg) {
       
try {
            OutputStreamWriter oStreamWriter =
new OutputStreamWriter(openFileOutput(fileName,
                   
Context.MODE_PRIVATE));
           
oStreamWriter.write(msg);
           
oStreamWriter.close();
       
} catch(FileNotFoundException e) {
            e.printStackTrace()
;
       
} catch (IOException e) {
            e.printStackTrace()
;
       
}
    }

   
private String readFile(String fileName) throws IOException {
        String fileContents =
"";
        try
{
            InputStream iStream = openFileInput(fileName)
;
            if
(iStream != null) {
                InputStreamReader iStreamReader =
new InputStreamReader(iStream);
                
BufferedReader bufferedReader = new BufferedReader(iStreamReader);
               
String temp = "";
               
StringBuffer sBuffer = new StringBuffer();
                while
((temp = bufferedReader.readLine()) != null) {
                    sBuffer.append(temp)
;
               
}
                iStream.close()
;
               
fileContents = sBuffer.toString();
           
}
        }
catch (FileNotFoundException e) {
            e.printStackTrace()
;
       
}
       
return fileContents;
    
}

    public void btnClick(View view) {
       
try {
            writeFile(
"testFile.txt", "testtttttttt");
           
String rFile = readFile("testFile.txt");
           
textView.setText(rFile);
       
} catch (IOException e) {
            e.printStackTrace()
;
       
}
    }
}

 

- copy coding -



안드로이드 프로그램에서 제일 많이 사용하게 되는 View 인터페이스 TextView EditText 이용하여 엔터키 이벤트 사용 방법을 알아 봅니다

엔터키 이벤트는 EditText에서 발생 하는데 여러가지 key event 들이 발생 하면 그중 enter event 선택하여 처리를 하는 것으로 2가지 방법을 이용하게 됩니다. 하나는 EditText 생성시 직접 이벤트 처리를 부여하는 방법이고 다른 하나는 implements 사용하여 OnKeyListener 상속받아 처리하는 방법 입니다최종 구현 상태는 아래 그림과 같습니다.


android enter key



1. 프로젝트 생성


실제로 프로젝트를 생성해 보도록 하겠습니다.


android enter key


Empty Activity 선택 하고


android enter key

 

적당한 프로젝트 명을 입력 합니다신규로 추가하는 프로그램 없이 프로젝트 생성시 기본적으로 생성되는 파일을 이용하여 구현합니다.

 

2. Layout 구현

 

먼저 activity_main.xml파일에 EditText 2 추가해 줍니다. id 적당히 입력을 해주면 됩니다하나는 생성할때 이벤트 처리 기능을 부여 하고 다른 하나는 OnKeyListener 이용한 처리에 사용하게 됩니다.

<TextView

        android:id="@+id/plain_text"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="hello world"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

 

    <EditText

        android:id="@+id/plain_text_input"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="112dp"

        android:hint="text1"

        android:inputType="text"

        app:layout_constraintTop_toTopOf="parent"

        tools:layout_editor_absoluteX="27dp" />

 

    <EditText

        android:id="@+id/plain_text_input2"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="168dp"

        android:hint="text2"

        android:inputType="text"

        app:layout_constraintTop_toTopOf="parent"

        tools:layout_editor_absoluteX="0dp" />

 

 

3. Java 기능 구현

 

MainActivity.java 에서 이벤트 처리 로직입니다.


3.1 첫번째 이벤트 처리 방법


첫번째는 onCreate()에서 EditText 생성할 엔터 이벤트 처리 로직을 부여하는 방법 입니다. EditText 생성 하고 바로 onKey() 기능을 추가하여  필요한 작업을 구현하면 됩니다.

@Override

    protected void onCreate(Bundle savedInstanceState) {

eText2 = (EditText) findViewById(R.id.plain_text_input2);

 

eText2.setOnKeyListener(new View.OnKeyListener() {

            @Override

            public boolean onKey(View v, int keyCode, KeyEvent event) {

                switch (keyCode) {

                    case KeyEvent.KEYCODE_ENTER:

                        txtView.setText(eText2.getText());

                        break;

                }

                return true;

            }

        });

}

 

구현된 작업은 EditText 입력한 내용을 TextView 출력 하게 하는 간단한 작업 입니다.

 

3.2 두번째 이벤트 처리 방법


두번째는 OnKeyListener 상속받아 onKey() 구현하는 방법 입니다. class implements OnKeyListener 상속하고 Override onKey() 구현을 하면 됩니다.

public class MainActivity extends AppCompatActivity implements View.OnKeyListener {

 

@Override

protected void onCreate(Bundle savedInstanceState) {

eText1 = (EditText) findViewById(R.id.plain_text_input);

    eText2 = (EditText) findViewById(R.id.plain_text_input2);

}

 

@Override

public boolean onKey(View v, int keyCode, KeyEvent event) {

         if(keyCode == KeyEvent.KEYCODE_ENTER) {

            switch (v.getId()) {

                case R.id.plain_text_input:

                    txtView.setText(eText1.getText());

                    break;

                case R.id.plain_text_input2:

                    txtView.setText(eText2.getText());

                    break;

            }

            return true;

        }

        return false;

}

 

구현된 내용은 EditText에서 이벤트를 받으면 엔터 이벤인가 확인 하고 2개의 EditText 어디에서 발생 하였는지 확인하여 입력한 내용을 TextView 출력 하게 하는 작업 입니다.

 


android enter key

위에 있는 결과는 두번째 EditText에서 엔터키 이벤트가 발생한것을 있습니다.

 

4. 전체 Source


4.1 activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context=".MainActivity">

    <TextView
       
android:id="@+id/plain_text"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="hello world"
       
app:layout_constraintBottom_toBottomOf="parent"
       
app:layout_constraintLeft_toLeftOf="parent"
       
app:layout_constraintRight_toRightOf="parent"
       
app:layout_constraintTop_toTopOf="parent" />

    <EditText
       
android:id="@+id/plain_text_input"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="112dp"
       
android:hint="text1"
       
android:inputType="text"
       
app:layout_constraintTop_toTopOf="parent"
       
tools:layout_editor_absoluteX="27dp" />

    <EditText
       
android:id="@+id/plain_text_input2"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="168dp"
       
android:hint="text2"
       
android:inputType="text"
       
app:layout_constraintTop_toTopOf="parent"
       
tools:layout_editor_absoluteX="0dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

4.2MainAcitivity.java


두가지 기능을 한곳에 담아 보았습니다.

package copycoding.tistory.texttest;

import
androidx.appcompat.app.AppCompatActivity;

import
android.os.Bundle;
import
android.view.KeyEvent;
import
android.view.View;
import
android.widget.EditText;
import
android.widget.TextView;

public class
MainActivity extends AppCompatActivity implements View.OnKeyListener {
    EditText
eText1, eText2;
   
TextView txtView;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
       
setContentView(R.layout.activity_main);

       
eText1 = (EditText) findViewById(R.id.plain_text_input);
       
eText2 = (EditText) findViewById(R.id.plain_text_input2);
       
txtView = (TextView) findViewById(R.id.plain_text);
       
eText1.setOnKeyListener(this);
       
eText2.setOnKeyListener(new View.OnKeyListener() {
           
@Override
           
public boolean onKey(View v, int keyCode, KeyEvent event) {
               
switch (keyCode) {
                   
case KeyEvent.KEYCODE_ENTER:
                       
txtView.setText(eText2.getText());
                        break;
               
}
               
return true;
           
}
        })
;
   
}

   
@Override
   
public boolean onKey(View v, int keyCode, KeyEvent event) {
        
if(keyCode == KeyEvent.KEYCODE_ENTER) {
           
switch (v.getId()) {
               
case R.id.plain_text_input:
                   
txtView.setText(eText1.getText());
                    break;
//                case R.id.plain_text_input2:
//                    txtView.setText(eText2.getText());
//                    break;
           
}
           
return true;
       
}
       
return false;
   
}
}

 

- copy coding - 



로그파일, xml등 프로그램을 하다보면 텍스트 문서를 불러왔는데 모두 한 줄로 이어져 있어 읽어 보기가 매우 힘든 경우가 있는데 공통된 반복 문구를 이용하여 줄바꿈(라인피드, 개행)하는 방법입니다알면 쉽고 모르면 한동안 방법을 찾아서 시간을 낭비해야 하는 경우가 있어 정리를 해봅니다.


editplus 줄바꿈


위와 같이 xml 파일이 모두 한 줄로 되어 있어 구조를 파악하기 상당히 힘든 경우에 “><” 이 중간 부분에 줄바꿈을 넣는다면 가독성이 좋아지겠죠.

그럼 우리가 기본적으로 생각하는 방법으로 바꾸기 명령을 이용하여 변경을 해 봅니다.

 

메뉴에서

검색 > 바꾸기

또는 단축 키

Ctrl + H

를 하여 바꾸기 창을 열고


editplus 줄바꿈


><>\n<으로 모두 바꿈 버튼을 클릭 해 봅니다.

 

안타깝지만 줄바꿈이 되지 않고 문장에 “\n”이 추가되어 있습니다.


editplus 줄바꿈


이렇게 특수 기호를 이용한 바꾸기를 하는 경우에는


editplus 줄바꿈


그림과 같이 정규식 항목을 체크하고 작업을 해야 합니다.

다시 한번 모두 바꿈 버튼을 클릭 합니다.


editplus 줄바꿈


원하는 줄바꿈 작업이 완료 되었습니다. 어떤 내용인지 편하게 볼 수 있게 되었습니다.


- copy coding -


안드로이드 스튜디오를 처음 설치할 때 배경에 대한 테마를 선택하도록 되어 있습니다하얀 바탕과 검은 바탕 중 어떤걸 선택 할지 조금 고민을 하게 되는데 대부분 기본으로 설정되어 있는 검은 색의 Darcula를 선택하고 넘어 갑니다.

그런데 코딩을 하다 보면 환경에 따라 또는 기호에 따라 하얀색 바탕이 편할 때도 있습니다개인적으로는 낮에는 검은 배경, 밤에는 하얀색 배경이 글씨를 보는데 눈의 피로를 덜 하게 되는 것 같습니다. 현재는 Darcula로 설정이 되어 있습니다.


android theme


테마 설정 변경은 간단합니다메뉴에서


 File > Settings...


를 선택 하면 


android theme


Settings 팝업 창이 나타나고


android theme


좌측 메뉴에서


Appearance & Behavior > Appearance


를 찾아서 클릭 합니다. 이제 우측 첫 번째 항목에

Theme:를 확장해 주면 Darcula, High contrast, IntelliJ 중 하나를 선택 할 수 있습니다.

 

먼저 High contrast를 선택하고 하단에 있는 OK 버튼을 클릭해 봅니다.


android theme


밋밋하던 개발 환경이 조금 강렬해 졌습니다. 대신 눈은 피곤해질것 같네요.


다시 Settings 창을 열고


android theme


이번에는 IntelliJ 를 선택 하고 OK 버튼을 클릭 합니다.


android theme


흰색 바탕의 편집 모드로 변경이 되었습니다

각자 눈의 피로가 덜 할 수 있는 테마를 골라서 사용해 보세요.


- copy coding -


123456···61

+ Recent posts