Advertisement
Leedwon

Untitled

Nov 23rd, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. public class MainActivity extends AppCompatActivity {
  2.  
  3.     final String fileName = new String("myFile.txt");
  4.  
  5.     TextView mTextView;
  6.  
  7.     EditText mEditText;
  8.  
  9.     Button mSaveButton;
  10.  
  11.     Button mLoadButton;
  12.  
  13.     @Override
  14.     protected void onCreate(Bundle savedInstanceState) {
  15.         super.onCreate(savedInstanceState);
  16.         setContentView(R.layout.activity_main);
  17.  
  18.         mTextView = findViewById(R.id.textView);
  19.  
  20.         mEditText = findViewById(R.id.editText);
  21.  
  22.         mSaveButton = findViewById(R.id.saveFile);
  23.  
  24.         mLoadButton = findViewById(R.id.loadFile);
  25.  
  26.         final File newFile = new File(getFilesDir(), fileName);
  27.  
  28.         final String mTextToSave = mEditText.getText().toString();
  29.  
  30.         mSaveButton.setOnClickListener(new View.OnClickListener() {
  31.             @Override
  32.             public void onClick(View view) {
  33.                 try{
  34.                     FileOutputStream outputStream = new FileOutputStream(newFile);
  35.                     outputStream.write(mTextToSave.getBytes());
  36.                     outputStream.close();
  37.                 } catch (Exception e) {
  38.                     Log.e("SaveButton", "Exception");
  39.                 }
  40.             }
  41.         });
  42.  
  43.         mLoadButton.setOnClickListener(new View.OnClickListener(){
  44.             @Override
  45.             public void onClick(View view) {
  46.                 mTextView.setText(new String (ReadFile(newFile)));
  47.             }
  48.         });
  49.     }
  50.  
  51.     private String ReadFile(File newFile){
  52.         String result = "";
  53.         try{
  54.             String message;
  55.             FileInputStream inputstream = new FileInputStream(newFile);
  56.             InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
  57.             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  58.             StringBuffer stringBuffer = new StringBuffer();
  59.  
  60.             while((message = bufferedReader.readLine()) != null){
  61.  
  62.                 stringBuffer.append(message + '\n');
  63.             }
  64.             result = stringBuffer.toString();
  65.             inputstream.close();
  66.         } catch (Exception e) {
  67.             Log.e("LoadButton", "Exception");
  68.         }
  69.  
  70.         return result;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement