Evgenii Legotckoi
July 31, 2015, 7:06 a.m.

The file on the Android OS. Read and write operations

Read and write operations to file are standard functionality of any applications that are logging the events, work with files, up to the transfer of data over the network. In this article, we consider methods of recording information in the files, and read from a file recorded line.

Project structure

Esthetic changes to the standard buttons or ListView will not be made in this lesson, since we work with what is hidden from the eyes of the user, namely, to work with files.

The entire structure of the project respectively is at this time only one class: MainActivity

Also, the project contains the following resource files:

  1. activity_main.xml
  2. strings.xml
  3. styles.xml - in the file does not have any changes relating to a project.

In addition, changes in the AndroidManifest.xml file. The file you need to add the following two lines. This permits the application - perform read and write operations to an external storage (ie SD Card phone) in modern smartphones based on the Android operating system in the majority of cases, the recording of information is carried out in an external drive, though typical user finds the drive internal, because it is built, but in terms of operating systems, this drive (ie SD Card) is an external drive. This article will not be considered an option to work with a true inner drive.

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="ru.evileg.workwithfiles" >
  3.  
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  5. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  6.  
  7. ...
  8.  
  9. </manifest>

Formation apps layout

activity_main.xml

Layout main Activiti, which will be the work of our application. This markup is present only two buttons (Button) and a text box (TextView), in which we will display information stored in the file.

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:paddingLeft="@dimen/activity_horizontal_margin"
  5. android:paddingRight="@dimen/activity_horizontal_margin"
  6. android:paddingTop="@dimen/activity_vertical_margin"
  7. android:paddingBottom="@dimen/activity_vertical_margin"
  8. android:background="#ffffff"
  9. android:orientation="vertical"
  10. tools:context=".MainActivity">
  11.  
  12. <Button
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:text="@string/write_file"
  16. android:id="@+id/buttonWrite"
  17. android:layout_gravity="center_horizontal" />
  18.  
  19. <Button
  20. android:layout_width="match_parent"
  21. android:layout_height="wrap_content"
  22. android:text="@string/read_file"
  23. android:id="@+id/buttonRead"
  24. android:layout_gravity="center_horizontal" />
  25.  
  26. <TextView
  27. android:layout_width="match_parent"
  28. android:layout_height="match_parent"
  29. android:id="@+id/textView"
  30. android:textSize="26sp"
  31. android:layout_gravity="center_horizontal" />
  32. </LinearLayout>

strings.xml

The resource file text in the Android OS. Preparation of all the lines that are used in your application in the file, is not only a good habit, but a prerequisite for the development of high-quality applications. Because, if you discipline yourself to keep all such information in the file, then it will pay off later when you will make the translation into other languages. Especially because in Android Studio has convenient features for this.

  1. <resources>
  2. <string name="app_name">Work With Files</string>
  3.  
  4. <string name="hello_world">Hello world!</string>
  5. <string name="action_settings">Settings</string>
  6.  
  7. <string name="write_done">Запись выполнена</string>
  8. <string name="write_file">Записать данные в файл</string>
  9. <string name="read_file">Считать данные из файла</string>
  10. </resources>

styles.xml

In this file, there are no changes related to the project. But when you create a standard project design theme is not rendered Android Studio. Issued error in preview mode and in design. To avoid this, list the following information instead of the old.

  1. <resources>
  2.  
  3. <!-- Base application theme. -->
  4. <style name="AppTheme" parent="Base.Theme.AppCompat.Light"/>
  5.  
  6. </resources>

The main project class - MainActivity.java

Today this class is concentrated the whole program code. In this class, made the formation of the appearance of the main Activiti and organized work with files.

  1. package ru.evileg.workwithfiles;
  2.  
  3. import android.os.Bundle;
  4. import android.os.Environment;
  5. import android.support.v7.app.AppCompatActivity;
  6. import android.view.Menu;
  7. import android.view.MenuItem;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.TextView;
  11. import android.widget.Toast;
  12.  
  13. import java.io.BufferedReader;
  14. import java.io.File;
  15. import java.io.FileInputStream;
  16. import java.io.FileNotFoundException;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19. import java.io.InputStreamReader;
  20.  
  21.  
  22. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  23.  
  24. /*
  25. * Create a permanent constants for convenience, to declare the TextView,
  26.   * which should be available in several class methods
  27. */
  28. private static final String fileName = "hello.txt";
  29. private static final String text = "Hello World";
  30. private static TextView textView;
  31.  
  32. @Override
  33. protected void onCreate(Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.activity_main);
  36.  
  37. /*
  38. * We declare and initialize Buttons,
  39. * and initialize the TextView
  40. * Also in the Activiti implement the method of pressing the event listener,
  41. * ie OnClickListener, which attaches itself to the buttons
  42. */
  43. textView = (TextView) this.findViewById(R.id.textView);
  44. Button buttonWrite = (Button) this.findViewById(R.id.buttonWrite);
  45. Button buttonRead = (Button) this.findViewById(R.id.buttonRead);
  46. buttonWrite.setOnClickListener(this);
  47. buttonRead.setOnClickListener(this);
  48.  
  49. }
  50.  
  51. @Override
  52. public boolean onCreateOptionsMenu(Menu menu) {
  53. // Inflate the menu; this adds items to the action bar if it is present.
  54. getMenuInflater().inflate(R.menu.menu_main, menu);
  55. return true;
  56. }
  57.  
  58. @Override
  59. public boolean onOptionsItemSelected(MenuItem item) {
  60. // Handle action bar item clicks here. The action bar will
  61. // automatically handle clicks on the Home/Up button, so long
  62. // as you specify a parent activity in AndroidManifest.xml.
  63. int id = item.getItemId();
  64.  
  65. //noinspection SimplifiableIfStatement
  66. if (id == R.id.action_settings) {
  67. return true;
  68. }
  69.  
  70. return super.onOptionsItemSelected(item);
  71. }
  72.  
  73. /*
  74. * Processor keystrokes. When the button is defined by its ID through getID () method
  75. */
  76. @Override
  77. public void onClick(View v) {
  78.  
  79. switch (v.getId()){
  80. case R.id.buttonWrite:
  81. writeFile();
  82. break;
  83. case R.id.buttonRead:
  84. readFile();
  85. break;
  86. default:
  87. break;
  88. }
  89. }
  90.  
  91. private void writeFile() {
  92. try {
  93. /*
  94. * Create a file object, and the path to be the method of transfer class Environment
  95. * Contacting goes as stated above to an external drive
  96. */
  97. File myFile = new File(Environment.getExternalStorageDirectory().toString() + "/" + fileName);
  98. myFile.createNewFile(); // It creates the file if it has not been created
  99. FileOutputStream outputStream = new FileOutputStream(myFile); // Then create a stream for writing
  100. outputStream.write(text.getBytes()); // and produce directly record
  101. outputStream.close();
  102. /*
  103. * Call Toast messages are not related to the topic.
  104. * Just for the convenience of the visual inspection method of execution in the annex
  105. */
  106. Toast.makeText(this, R.string.write_done, Toast.LENGTH_SHORT).show();
  107. } catch (Exception e) {
  108. e.printStackTrace();
  109. }
  110. }
  111.  
  112. private void readFile() {
  113. /*
  114. * Similarly, the file object is created
  115. */
  116. File myFile = new File(Environment.getExternalStorageDirectory().toString() + "/" + fileName);
  117. try {
  118. FileInputStream inputStream = new FileInputStream(myFile);
  119. /*
  120. * Buffer data from the input file stream
  121. */
  122. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  123. /*
  124. * Class to create strings from character sequences
  125. */
  126. StringBuilder stringBuilder = new StringBuilder();
  127. String line;
  128. try {
  129. /*
  130. * We produce by-line reading of data from a file into a string constructor
  131. * After the data is finished, we produce the output text in the TextView
  132. */
  133. while ((line = bufferedReader.readLine()) != null){
  134. stringBuilder.append(line);
  135. }
  136. textView.setText(stringBuilder);
  137. } catch (IOException e) {
  138. e.printStackTrace();
  139. }
  140. } catch (FileNotFoundException e) {
  141. e.printStackTrace();
  142. }
  143. }
  144. }

Result

If in the process of studying the material did not have any problems and errors, by pressing the record button in the file will create a new file, and will be made "Hello World" string entry. When you click the button reading a saved information will be displayed in a text file. The process is shown in the screenshots below.

By pressing the button in the recording information file

Filing

Reading from a file is done by pressing the corresponding button. This text is displayed in a TextView

Created hello.txt file in the file manager

Recommended articles on this topic

By article asked0question(s)

2
A
  • Nov. 6, 2017, 8:18 p.m.

Как я понял данное приложение сохраняет текст в один единственный файл - hello.txt. Хотел бы узнать как можно реализовать функцию создания новый текстовых файлов и их переименования, т.е после нажатия на кнопку сохранения будет создаваться новый текстовый файл, пользователь будет выбирать куда не телефоне его сохранить и сам же вводит имя файла. А так же как реализовать функцию выбора из каталога файлов, т. е при нажатие на кнопку "считать из файла" открывалась бы папка в которой у пользователя находятся другие текстовые документы и он мог их редактировать последующего редактирования.

Evgenii Legotckoi
  • Nov. 7, 2017, 1:41 a.m.

эххх... как это было давно и не правда )))) я с тех пор (через пару месяцев после этой статьи +-) на Java и не писал больше.
Вот если меня накроет не по-детски и я всё-таки начну писать сравнительные статьи Android: Java vs Qt , вот тогда что-нибудь интересное и вывалится на эту тему. А так пока... даже не знаю, что Вам ответить.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…