Wednesday, February 20, 2019

Java write data

In any class, choose a textView to set text.
Copy the code lines to below findViewByid.
String write="This is example text";
try {
FileOutputStream fos = openFileOutput("text.txt", Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fos);
     osw.append(write);
     osw.flush();
     osw.close();
      } catch (FileNotFoundException e) {            
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }  
Here we write a String to file name text.txt, to make sure the data has write, we read that file and set text to textView.
String read="";
try {
          String FILE_NAME = "text.txt";          
          FileInputStream fIS = openFileInput(FILE_NAME);              
          byte[] arrayData = new byte[fIS.available()];
          if((fIS.read(arrayData))!= -1){
          String fileContent = new String(arrayData);
          read=fileContent;
          tv.setText(read);
          }   
          fIS.close();             
          } catch (Exception e) {
              
               //Log.e("Error", e.toString());
          }
Run to see text has read success.
If you quit and reopen class many times, you will see many string add to textView, because file text.txt always there and programme continue to write many times.

No comments:

Post a Comment