Assalomu alaykum. Bugun sizlar bilan birgalikda Android Studio-da fayllar bilan ishlashning boshlang'ich tushunchalari haqida bilib olamiz. Demak, boshladik.

Activityning sozlamalari va dastur bilan ishlash sizga alohida turdagi (string, int) kichik ma'lumotlarni saqlashga imkon beradi, ammo katta hajmdagi ma'lumotlar bilan ishlash uchun, masalan, grafik fayllar, multimedia fayllari va boshqalar uchun biz fayl tizimiga kirishimiz kerak bo'ladi.

Android ilovasi o'z ma'lumotlarini /data/data/package_name katalogiga saqlaydi va ushbu katalogga nisbatan ish olib boriladi.

android.content.Context abstrakt sinfi fayllar bilan ishlashning bir qator metodlarini aniqlaydi:

  • deleteFile(String name): faylni o'chiradi.
  • fileList(): ilova katalogidagi /files katalogidagi barcha fayllarni oladi.
  • getCacheDir(): ilova katalogidagi cache katalogini oladi.
  • getDir(String dirName, int mode): ilova katalogidagi ma'lum bir katalogni oladi, agar bunday katalog bo'lmasa, u yaratiladi.
  • getExternalCacheDir(): qurilmaning tashqi fayl tizimidagi /cache papkasini oladi.
  • getExternalFilesDir(): qurilmaning tashqi fayl tizimining /files katalogini oladi.
  • getFileStreamPath(String filename): Fayl tizimidagi faylga absolyut yo'lni qaytaradi.
  • openFileInput(String filename): o'qish uchun faylni ochadi.
  • openFileOutput(String name, int mode): yozish uchun faylni ochadi.

Ilovada yaratilgan va tahrir qilingan barcha fayllar odatda ilova katalogidagi /files katalogida saqlanadi.

java.io paketidan standart Java sinflari fayllarni o'qish va yozish uchun ishlatiladi.

Shunday qilib, ilovada fayllarni o'qish-yozish funksiyasidan foydalanaylik.

Android Studio-da yangi ilova yarating va "Fayllar" deb nomlang. activity_main.xml faylini quyidagicha o'zgartiring:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/save_text"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4"
        android:gravity="start" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_margin="16dp"
        android:layout_weight="1"
        android:onClick="saveText"
        android:text="Saqlash" />

    <TextView
        android:id="@+id/open_text"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="80dp"
        android:layout_weight="4"
        android:gravity="start" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_margin="16dp"
        android:layout_weight="1"
        android:onClick="openText"
        android:text="Ochish" />
    
</LinearLayout>

EditText maydoni matn kiritish uchun, TextView esa avval saqlangan matnni namoyish qilish uchun. Matnni saqlash va ko'rsatish uchun ikkita tugma qo'shilgan.

Endi Activity kodida tugmachalarni bosganda faylni saqlash va o'qish uchun quyidagi kodni yozing:

package com.example.android.fayllar;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private final static String FILE_NAME = "content.txt";

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

    // faylni saqlash
    public void saveText(View view) {

        FileOutputStream fos = null;
        try {
            EditText textBox = findViewById(R.id.save_text);
            String text = textBox.getText().toString();

            fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
            fos.write(text.getBytes());
            Toast.makeText(this, "Fayl saqlandi", Toast.LENGTH_SHORT).show();
        } catch (IOException ex) {

            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException ex) {

                Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    // faylni ochish
    public void openText(View view) {

        FileInputStream fin = null;
        TextView textView = findViewById(R.id.open_text);
        try {
            fin = openFileInput(FILE_NAME);
            byte[] bytes = new byte[fin.available()];
            fin.read(bytes);
            String text = new String(bytes);
            textView.setText(text);
        } catch (IOException ex) {

            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {

            try {
                if (fin != null)
                    fin.close();
            } catch (IOException ex) {

                Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Saqlash tugmachasini bosish FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE) chiqish oqimini hosil qiladi.

Bizni kodda, kiritilgan matn "content.txt" faylida saqlanadi. Bunda MODE_PRIVATE rejimidan foydalanilgan.

Tizim ikki xil rejimdagi fayllarni yaratishga imkon beradi:

  • MODE_PRIVATE: fayllarga faqat ilova egasi kirishi mumkin (standart rejim).
  • MODE_APPEND: fayl oxiriga ma'lumotlar qo'shilishi mumkin.

Bizni kodda, agar "content.txt" fayli allaqachon mavjud bo'lsa, uning ustiga yoziladi. Agar bizga fayl qo'shish kerak bo'lsa, unda MODE_APPEND rejimidan foydalanishimiz kerak bo'ladi:

FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);

Faylni o'qish uchun FileInputStream kirish oqimi ishlatiladi:

FileInputStream fin = openFileInput(FILE_NAME);

Natijada, saqlash tugmachasini bosgandan so'ng, barcha matn /data/data/package_name/files/content.txt faylida saqlanadi.

Endi ilovani ishga tushiring va natijani ko'ring:

 

Endi matn kiriting va "SAQLASH" tugmasini bosing:

 

Endi ilovadan chiqib keting va ilovani yoping. Endi yana ilovaga kiring va "OCHISH" tugmasini bosing:

 

Sizlar bilan ulashmoqchi bo'lgan ma'lumotlarim shulardan iborat edi. Sizlarga foydali bo'ldi, degan umiddaman.

 

"ONE MILLION UZBEK CODERS" BILAN YANGI MARRALARNI ZABT ETING!