Lesson 75. Data Storage. Working with files.

Lesson 75. Data Storage. Working with files.


In this lesson:

– work with files

Working with files in Android is not much different from that in Java. In this tutorial, we’ll look at how to write / read a file to internal memory and an SD card.

Let’s create a project:

Project name: P0751_Files
Build Target: Android 2.3.3
Application name: Files
Package name: ru.startandroid.develop.p0751files
Create Activity: MainActivity

let’s fill it strings.xml:



    P0751_Files
    Записать файл
    Прочесть файл
    Записать файл на SD
    Прочесть файл с SD

we draw a screen main.xml:



    
        
        
    
    
        
        
    

4 buttons whose contents are clear on the text on them.

MainActivity.java:

package ru.startandroid.develop.p0751files;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

  final String LOG_TAG = "myLogs";

  final String FILENAME = "file";

  final String DIR_SD = "MyFiles";
  final String FILENAME_SD = "fileSD";

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

  public void onclick(View v) {
    switch (v.getId()) {
    case R.id.btnWrite:
      writeFile();
      break;
    case R.id.btnRead:
      readFile();
      break;
    case R.id.btnWriteSD:
      writeFileSD();
      break;
    case R.id.btnReadSD:
      readFileSD();
      break;
    }
  }

  void writeFile() {
    try {
      // отрываем поток для записи
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
          openFileOutput(FILENAME, MODE_PRIVATE)));
      // пишем данные
      bw.write("Содержимое файла");
      // закрываем поток
      bw.close();
      Log.d(LOG_TAG, "Файл записан");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  void readFile() {
    try {
      // открываем поток для чтения
      BufferedReader br = new BufferedReader(new InputStreamReader(
          openFileInput(FILENAME)));
      String str = "";
      // читаем содержимое
      while ((str = br.readLine()) != null) {
        Log.d(LOG_TAG, str);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  void writeFileSD() {
    // проверяем доступность SD
    if (!Environment.getExternalStorageState().equals(
        Environment.MEDIA_MOUNTED)) {
      Log.d(LOG_TAG, "SD-карта не доступна: " + Environment.getExternalStorageState());
      return;
    }
    // получаем путь к SD
    File sdPath = Environment.getExternalStorageDirectory();
    // добавляем свой каталог к пути
    sdPath = new File(sdPath.getAbsolutePath() + "https://startandroid.ru/" + DIR_SD);
    // создаем каталог
    sdPath.mkdirs();
    // формируем объект File, который содержит путь к файлу
    File sdFile = new File(sdPath, FILENAME_SD);
    try {
      // открываем поток для записи
      BufferedWriter bw = new BufferedWriter(new FileWriter(sdFile));
      // пишем данные
      bw.write("Содержимое файла на SD");
      // закрываем поток
      bw.close();
      Log.d(LOG_TAG, "Файл записан на SD: " + sdFile.getAbsolutePath());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  void readFileSD() {
    // проверяем доступность SD
    if (!Environment.getExternalStorageState().equals(
        Environment.MEDIA_MOUNTED)) {
      Log.d(LOG_TAG, "SD-карта не доступна: " + Environment.getExternalStorageState());
      return;
    }
    // получаем путь к SD
    File sdPath = Environment.getExternalStorageDirectory();
    // добавляем свой каталог к пути
    sdPath = new File(sdPath.getAbsolutePath() + "https://startandroid.ru/" + DIR_SD);
    // формируем объект File, который содержит путь к файлу
    File sdFile = new File(sdPath, FILENAME_SD);
    try {
      // открываем поток для чтения
      BufferedReader br = new BufferedReader(new FileReader(sdFile));
      String str = "";
      // читаем содержимое
      while ((str = br.readLine()) != null) {
        Log.d(LOG_TAG, str);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

IN onclick we process pressing 4 buttons and call appropriate methods.

writeFile – write file to internal memory. The openFileOutput method is used, which takes the file name and write mode as input: MODE_PRIVATE – the file is accessible only to this application, MODE_WORLD_READABLE – the file is accessible for everyone to read, MODE_WORLD_WRITEABLE – the file is accessible for writing to everyone, MODE_APPEND – the file will be added and not added .

readFile – read file from internal memory. We use the openFileInput method, which accepts the filename. Here and in the internal file method, you can only specify the file name, and the directory for your files is already allocated to you.

writeFileSD – burn file to SD. We use the getExternalStorageState method to get the status of the SD card. Here you can see what are the statuses. We need MEDIA_MOUNTED – when the SD card is inserted and ready to go. Next, we get the path to the SD card (getExternalStorageDirectory method), add our directory and file name, create a directory and write the data to a file.

readFileSD – reading a file from SD. Everything is similar to the previous method, only the file is not written, but read.

Remainder to add permission to work with files on SD – android.permission.WRITE_EXTERNAL_STORAGE.

We’ll save everything and run it. We see a screen with 4 buttons:

Internal memory

press the button save file. We see in a beam:

the file is recorded

Let’s check. we go to File Explorer (Window> Show View> Other> Android> File Explorer) and open the folder there data / data / ru.startandroid.develop.p0751files / files and we see our file there file.

Let’s go back to the emulator. press read the file and in the beam we see:

the contents of the file

This is the text that we have written to the file.

SD card

now press Save file to SD.

In the beam we see:

The file is written to SD: / mnt / sdcard / MyFiles / fileSD

We check. we go to FileExplorer and open the folder there mnt / sdcard / MyFiles / and it contains a file fileSD.

Go back to the emulator and click the Read file from SD button. In the beam we see:

The contents of the file on SD

We wrote down this text.

mnt / sdcard – this path usually leads to the contents of the SD card. Maybe you will have another one.

In general, you use standard java mechanisms when working with files on SD. And when working with an internal repository, you can use Activity shell methods for convenience:

openFileOutput – open file for recording

openFileInput – open file for reading

deleteFile – delete the file

And there is a getFilesDir method – returns a File object corresponding to the directory for your application’s files. Use it to work directly without shell methods.

I will not describe the details of work in java with the file system here. In our forum, the SKR user made a great note about working with files. Most likely, you will find everything you need there.

If you have an SD card check that the card is unavailable (see Log), then make sure the AVD property is set to Size or File for the SDCard. If yes, try restarting AVD.

In the next lesson:

– create a tab with tabs
– use the icon in the tab name
– we use the tab switch handler




Discuss in the forum [139 replies]

Leave a Comment