Поиск по сайту:

Учебное пособие по примерам внутренней памяти Android


Сегодня мы рассмотрим внутреннее хранилище Android. Android предлагает несколько структурированных способов хранения данных. К ним относятся

  • Общие настройки
  • Внутренняя память
  • Внешнее хранилище
  • Хранилище SQLite
  • Хранение через сетевое подключение (в облаке)

В этом уроке мы рассмотрим сохранение и чтение данных в файлы с использованием внутренней памяти Android.

Внутренняя память Android

Внутреннее хранилище Android — это хранилище личных данных в памяти устройства. По умолчанию сохранение и загрузка файлов во внутреннюю память являются частными для приложения, и другие приложения не будут иметь доступа к этим файлам. Когда пользователь удаляет приложения, внутренние сохраненные файлы, связанные с приложением, также удаляются. Однако обратите внимание, что некоторые пользователи рутируют свои телефоны Android, получая доступ суперпользователя. Эти пользователи смогут читать и записывать любые файлы, которые они пожелают.

Чтение и запись текстового файла во внутренней памяти Android

Android предлагает openFileInput и openFileOutput из классов ввода-вывода Java для изменения потоков чтения и записи из и в локальные файлы.

  • openFileOutput(): This method is used to create and save a file. Its syntax is given below:

    FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);
    

    The method openFileOutput() returns an instance of FileOutputStream. After that we can call write method to write data on the file. Its syntax is given below:

    String str = "test data";
    fOut.write(str.getBytes());
    fOut.close();
    
  • openFileInput(): This method is used to open a file and read it. It returns an instance of FileInputStream. Its syntax is given below:

    FileInputStream fin = openFileInput(file);
    

    After that, we call read method to read one character at a time from the file and then print it. Its syntax is given below:

    int c;
    String temp="";
    while( (c = fin.read()) != -1){
       temp = temp + Character.toString((char)c);
    }
    
    fin.close();
    

    In the above code, string temp contains all the data of the file.

  • Note that these methods do not accept file paths (e.g. path/to/file.txt), they just take simple file names.

Структура проекта внутреннего хранилища Android

Пример кода внутреннего хранилища Android

Макет xml содержит EditText для записи данных в файл, а также кнопки записи и чтения. Обратите внимание, что методы onClick определены в XML-файле только так, как показано ниже: activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:padding="5dp"
        android:text="Android Read and Write Text from/to a File"
        android:textStyle="bold"
        android:textSize="28sp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:minLines="5"
        android:layout_margin="5dp">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Write Text into File"
        android:onClick="WriteBtn"
        android:layout_alignTop="@+id/button2"
        android:layout_alignRight="@+id/editText1"
        android:layout_alignEnd="@+id/editText1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read Text From file"
        android:onClick="ReadBtn"
        android:layout_centerVertical="true"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignStart="@+id/editText1" />

</RelativeLayout>

MainActivity содержит реализацию чтения и записи в файлы, как было объяснено выше.

package com.journaldev.internalstorage;


import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends Activity {

    EditText textmsg;
    static final int READ_BLOCK_SIZE = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textmsg=(EditText)findViewById(R.id.editText1);
    }

    // write text to file
    public void WriteBtn(View v) {
        // add-write text into file
        try {
            FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
            outputWriter.write(textmsg.getText().toString());
            outputWriter.close();

            //display file saved message
            Toast.makeText(getBaseContext(), "File saved successfully!",
                    Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Read text from file
    public void ReadBtn(View v) {
        //reading text from file
        try {
            FileInputStream fileIn=openFileInput("mytextfile.txt");
            InputStreamReader InputRead= new InputStreamReader(fileIn);

            char[] inputBuffer= new char[READ_BLOCK_SIZE];
            String s="";
            int charRead;

            while ((charRead=InputRead.read(inputBuffer))>0) {
                // char to string conversion
                String readstring=String.copyValueOf(inputBuffer,0,charRead);
                s +=readstring;
            }
            InputRead.close();
            textmsg.setText(s);
            

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Где находится файл?

Скачать пример проекта внутреннего хранилища Android