package com.example.admin.s20172285_0910_03;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.PrintWriter;

public class MainActivity extends AppCompatActivity {
    EditText edit;
    File file;
    File path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        path = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS);
        file = new  File(path,"test.txt");

        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)==false){
            Toast.makeText(getApplicationContext(), "외부 스토리지 실패", Toast.LENGTH_SHORT).show();
        }
        edit =(EditText) findViewById(R.id.EditText01);
        final Button readButton = (Button) findViewById(R.id.read);
        Button writeButton = (Button) findViewById(R.id.write);

        readButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    FileReader in = new FileReader(file);
                    StringBuffer buffer = new StringBuffer();
                    BufferedReader reader = new BufferedReader(in);

                    String str = reader.readLine();
                    while (str !=null) {
                        buffer.append(str + "\n");
                        str = reader.readLine();
                    }
                    edit.setText(new String(buffer));
                    reader.close();
                    Toast.makeText(getApplicationContext(),"Read",
                            Toast.LENGTH_LONG).show();
                }catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Read Field", Toast.LENGTH_LONG).show();
                }
            }
        });
        writeButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {
                    FileWriter wr = new FileWriter(file, false);
                    PrintWriter writer = new PrintWriter(wr);
                    writer.print(edit.getText().toString());
                    writer.close();
                    Toast.makeText(getApplicationContext(), "Write", Toast.LENGTH_LONG).show();
                }
                catch (Exception e){
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Write Field", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}
