Evgenii Legotckoi
Evgenii LegotckoiJuly 30, 2015, 9:06 p.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.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ru.evileg.workwithfiles" >

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

...

</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.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/write_file"
        android:id="@+id/buttonWrite"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/read_file"
        android:id="@+id/buttonRead"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/textView"
        android:textSize="26sp"
        android:layout_gravity="center_horizontal" />
</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.

<resources>
    <string name="app_name">Work With Files</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string name="write_done">Запись выполнена</string>
    <string name="write_file">Записать данные в файл</string>
    <string name="read_file">Считать данные из файла</string>
</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.

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.Theme.AppCompat.Light"/>

</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.

package ru.evileg.workwithfiles;

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    /*
     * Create a permanent constants for convenience, to declare the TextView, 
     * which should be available in several class methods
     */
    private static final String fileName = "hello.txt";
    private static final String text = "Hello World";
    private static TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*
         * We declare and initialize Buttons,
         * and initialize the TextView
         * Also in the Activiti implement the method of pressing the event listener,
         * ie OnClickListener, which attaches itself to the buttons
         */
        textView = (TextView) this.findViewById(R.id.textView);
        Button buttonWrite = (Button) this.findViewById(R.id.buttonWrite);
        Button buttonRead = (Button) this.findViewById(R.id.buttonRead);
        buttonWrite.setOnClickListener(this);
        buttonRead.setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /*
     * Processor keystrokes. When the button is defined by its ID through getID () method
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.buttonWrite:
                writeFile();
                break;
            case R.id.buttonRead:
                readFile();
                break;
            default:
                break;
        }
    }

    private void writeFile() {
        try {
            /*
             * Create a file object, and the path to be the method of transfer class Environment
             * Contacting goes as stated above to an external drive
             */
            File myFile = new File(Environment.getExternalStorageDirectory().toString() + "/" + fileName);
            myFile.createNewFile();                                         // It creates the file if it has not been created
            FileOutputStream outputStream = new FileOutputStream(myFile);   // Then create a stream for writing
            outputStream.write(text.getBytes());                            // and produce directly record
            outputStream.close();
            /*
             * Call Toast messages are not related to the topic.
             * Just for the convenience of the visual inspection method of execution in the annex
             */
            Toast.makeText(this, R.string.write_done, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void readFile() {
        /*
         * Similarly, the file object is created
         */
        File myFile = new File(Environment.getExternalStorageDirectory().toString() + "/" + fileName);
        try {
            FileInputStream inputStream = new FileInputStream(myFile);
            /*
             * Buffer data from the input file stream
             */
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            /*
             * Class to create strings from character sequences
             */
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            try {
                /*
                 * We produce by-line reading of data from a file into a string constructor
                 * After the data is finished, we produce the output text in the TextView
                 */
                while ((line = bufferedReader.readLine()) != null){
                    stringBuilder.append(line);
                }
                textView.setText(stringBuilder);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

A
  • Nov. 6, 2017, 9:18 a.m.

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

Evgenii Legotckoi
  • Nov. 6, 2017, 2:41 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 23, 2024, 3:51 p.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks