Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Кашина_РМП_ЛБ15

.docx
Скачиваний:
0
Добавлен:
22.09.2026
Размер:
121 Кб
Скачать
☆

Министерство науки и высшего образования Российской Федерации Федеральное государственное бюджетное образовательное учреждение высшего образования

«Владимирский государственный университет

имени Александра Григорьевича и Николая Григорьевича Столетовых» (ВлГУ)

Колледж инновационных технологий и предпринимательства

КАФЕДРА ФИЗИКИ И ПРИКЛАДНОЙ МАТЕМАТИКИ

Лабораторная работа № 15

по МДК 01.03 «Разработка мобильных приложений»

на тему: «Работа с файлами Андроид.»

Выполнил

студент группы ИПсп-123

Кашина Д. А.

Принял

Красильщикова В.В.

Владимир, 2026 г.

Цель работы: получить навыки создания Android-приложений с использованием файлов.

Ход работы:

  1. MainActivity.java

package com.example.laba15;

import android.app.AlertDialog;

import android.os.Bundle;

import android.view.ContextMenu;

import android.view.Menu;

import android.view.MenuInflater;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.widget.Toolbar;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

private EditText editText;

private TextView textView;

private Button btnSave, btnLoad;

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

private String lastSavedText = ""; // Для отслеживания последнего сохраненного текста

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Настройка Toolbar

Toolbar toolbar = findViewById(R.id.toolbar);

if (toolbar != null) {

setSupportActionBar(toolbar);

}

editText = findViewById(R.id.editText);

textView = findViewById(R.id.textView);

btnSave = findViewById(R.id.btnSave);

btnLoad = findViewById(R.id.btnLoad);

// Регистрируем контекстное меню

registerForContextMenu(editText);

registerForContextMenu(textView);

// Обработчики кнопок

btnSave.setOnClickListener(v -> saveText());

btnLoad.setOnClickListener(v -> loadText());

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.menu_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(@NonNull MenuItem item) {

int id = item.getItemId();

if (id == R.id.action_save) {

saveText();

return true;

} else if (id == R.id.action_load) {

loadText();

return true;

} else if (id == R.id.action_clear) {

clearFile();

return true;

} else if (id == R.id.action_about) {

showAboutDialog();

return true;

}

return super.onOptionsItemSelected(item);

}

/**

* Сохранение текста в файл (только в файл, без отображения)

*/

private void saveText() {

String text = editText.getText().toString();

try {

FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE);

// Сохраняем текст как есть (включая пустую строку)

fos.write(text.getBytes());

fos.close();

// Запоминаем что сохранили

lastSavedText = text;

// Показываем сообщение

if (text.isEmpty()) {

Toast.makeText(this, "✓ Пустая строка сохранена в файл", Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(this, "✓ Текст сохранен в файл", Toast.LENGTH_SHORT).show();

}

// НЕ загружаем текст автоматически, ждем кнопку "Загрузить"

} catch (IOException e) {

Toast.makeText(this, "✗ Ошибка сохранения", Toast.LENGTH_SHORT).show();

e.printStackTrace();

}

}

private void loadText() {

try {

FileInputStream fis = openFileInput(FILE_NAME);

InputStreamReader isr = new InputStreamReader(fis);

BufferedReader br = new BufferedReader(isr);

StringBuilder sb = new StringBuilder();

String line;

while ((line = br.readLine()) != null) {

sb.append(line).append("\n");

}

br.close();

isr.close();

fis.close();

String loadedText = sb.toString();

// Убираем последний перевод строки, если он есть

if (loadedText.endsWith("\n")) {

loadedText = loadedText.substring(0, loadedText.length() - 1);

}

// Отображаем текст (пустой или непустой)

textView.setText(loadedText);

if (loadedText.isEmpty()) {

Toast.makeText(this, "Загружена пустая строка", Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(this, "Текст загружен из файла", Toast.LENGTH_SHORT).show();

}

} catch (IOException e) {

textView.setText("Файл не найден");

Toast.makeText(this, "Файл не существует", Toast.LENGTH_SHORT).show();

}

}

private void clearFile() {

try {

FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE);

fos.write("".getBytes()); // Записываем пустую строку

fos.close();

lastSavedText = "";

Toast.makeText(this, "Файл очищен (пустая строка)", Toast.LENGTH_SHORT).show();

} catch (IOException e) {

Toast.makeText(this, "Ошибка очистки", Toast.LENGTH_SHORT).show();

}

}

/**

* Копирование текста из TextView в EditText

*/

private void copyToEdit() {

String displayedText = textView.getText().toString();

if (displayedText.equals("Файл не найден")) {

Toast.makeText(this, "Нет текста для копирования", Toast.LENGTH_SHORT).show();

return;

}

editText.setText(displayedText);

if (displayedText.isEmpty()) {

Toast.makeText(this, "Скопирована пустая строка", Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(this, "Текст скопирован в поле ввода", Toast.LENGTH_SHORT).show();

}

}

private void showAboutDialog() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("О программе")

.setMessage("Работа с файлами в Android\n\nВыполнила: Кашина Д.А.\nГруппа: ИПсп-123\n\nЛабораторная работа №15")

.setIcon(android.R.drawable.ic_dialog_info)

.setPositiveButton("OK", (dialog, which) -> dialog.dismiss())

.show();

}

@Override

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

getMenuInflater().inflate(R.menu.context_menu, menu);

if (v.getId() == R.id.editText) {

menu.setHeaderTitle("Действия с полем ввода");

} else {

menu.setHeaderTitle("Действия с файлом");

}

}

@Override

public boolean onContextItemSelected(@NonNull MenuItem item) {

int id = item.getItemId();

if (id == R.id.menu_save) {

saveText();

return true;

} else if (id == R.id.menu_load) {

loadText();

return true;

} else if (id == R.id.menu_copy) {

copyToEdit();

return true;

} else if (id == R.id.menu_clear_file) {

clearFile();

return true;

} else if (id == R.id.menu_clear_edit) {

editText.setText("");

Toast.makeText(this, "Поле ввода очищено", Toast.LENGTH_SHORT).show();

return true;

}

return super.onContextItemSelected(item);

}

}

  1. Activity_main.xml

<?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">

<androidx.appcompat.widget.Toolbar

android:id="@+id/toolbar"

android:layout_width="match_parent"

android:layout_height="?attr/actionBarSize"

android:background="#6200EE"

android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"

android:title="Работа с файлами"

android:titleTextColor="#FFFFFF"/>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Введите текст:"

android:textSize="16sp"

android:layout_marginBottom="4dp"/>

<EditText

android:id="@+id/editText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Можно оставить пустым..."

android:padding="10dp"

android:background="#F0F0F0"

android:layout_marginBottom="16dp"/>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal"

android:gravity="center">

<Button

android:id="@+id/btnSave"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:layout_marginRight="8dp"

android:text="Сохранить"/>

<Button

android:id="@+id/btnLoad"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:layout_marginLeft="8dp"

android:text="Загрузить"/>

</LinearLayout>

<View

android:layout_width="match_parent"

android:layout_height="1dp"

android:background="#CCCCCC"

android:layout_marginTop="20dp"

android:layout_marginBottom="10dp"/>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Сохраненный текст:"

android:textSize="16sp"

android:layout_marginBottom="4dp"/>

<ScrollView

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:background="#F5F5F5"

android:padding="8dp">

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Файл не найден"

android:textSize="14sp"

android:padding="8dp"/>

</ScrollView>

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Выполнилаav: Кашина Д.А."

android:textSize="14sp"

android:textColor="#6200EE"

android:gravity="center"

android:layout_marginTop="10dp"/>

</LinearLayout>

</LinearLayout>

  1. Context_menu.xml

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item

android:id="@+id/menu_save"

android:title="Сохранить в файл"/>

<item

android:id="@+id/menu_load"

android:title="Загрузить из файла"/>

<item

android:id="@+id/menu_copy"

android:title="Копировать в поле ввода"/>

<item

android:id="@+id/menu_clear_file"

android:title="Очистить файл"/>

<item

android:id="@+id/menu_clear_edit"

android:title="Очистить поле ввода"/>

</menu>

  1. Menu_main.xml

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto">

<item

android:id="@+id/action_save"

android:title="Сохранить"

android:icon="@android:drawable/ic_menu_save"

app:showAsAction="always"/>

<item

android:id="@+id/action_load"

android:title="Загрузить"

android:icon="@android:drawable/ic_menu_upload"

app:showAsAction="always"/>

<item

android:id="@+id/action_clear"

android:title="Очистить файл"

android:icon="@android:drawable/ic_menu_delete"

app:showAsAction="never"/>

<item

android:id="@+id/action_about"

android:title="О программе"

android:icon="@android:drawable/ic_menu_info_details"

app:showAsAction="never"/>

</menu>

  1. Результат работы программы

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