activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btnWrite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#50000000"
android:textColor="@color/black"
android:text="내장 메모리에 파일 쓰기"/>
<Button
android:id="@+id/btnRead"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#50000000"
android:textColor="@color/black"
android:text="내장 메모리에서 파일 읽기"/>
</LinearLayout>
MainActivity.java
package com.example.file;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnRead, btnWrite;
btnRead = (Button) findViewById(R.id.btnRead);
btnWrite = (Button) findViewById(R.id.btnWrite);
btnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try{
FileOutputStream outFs = openFileOutput("file.txt", Context.MODE_PRIVATE);
String str = "쿡북 안드로이드";
outFs.write(str.getBytes());
outFs.close();
Toast.makeText(getApplicationContext(),"file.txt가 생성됨", Toast.LENGTH_SHORT).show();
}catch (IOException e){}
}
});
btnRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
FileInputStream inFs = openFileInput("file.txt");
byte[] txt = new byte[30];
inFs.read(txt);
String str = new String(txt);
Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
inFs.close();
}catch (IOException e){
Toast.makeText(getApplicationContext(),"파일 없음",Toast.LENGTH_SHORT);
}
}
});
}
}
실행 화면
'안드로이드 > 연습' 카테고리의 다른 글
[Android] raw 폴더 파일 처리 (0) | 2021.08.24 |
---|---|
[Android] 간단 일기장 (0) | 2021.08.24 |
[Android] 사용자 정보 입력 (0) | 2021.08.23 |
[Android] Dialog2 (0) | 2021.08.23 |
[Android] Dialog (0) | 2021.08.23 |