package com.example.filestorage
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.IOException
class MainActivity : AppCompatActivity() {
private lateinit var inputEditText: EditText
private lateinit var saveButton: Button
private lateinit var loadButton: Button
private lateinit var contentTextView: TextView
private val filename = "myfile.txt"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
inputEditText = findViewById(R.id.inputEditText)
saveButton = findViewById(R.id.saveButton)
loadButton = findViewById(R.id.loadButton)
contentTextView = findViewById(R.id.contentTextView)
saveButton.setOnClickListener {
val textToSave = inputEditText.text.toString()
try {
openFileOutput(filename, MODE_PRIVATE).use { output ->
output.write(textToSave.toByteArray())
}
Toast.makeText(this, "File saved", Toast.LENGTH_SHORT).show()
inputEditText.text.clear()
} catch (e: IOException) {
Toast.makeText(this, "Error saving file", Toast.LENGTH_SHORT).show()
}
}
loadButton.setOnClickListener {
try {
val file = File(filesDir, filename)
if (file.exists()) {
val content = file.readText()
contentTextView.text = content
Toast.makeText(this, "File loaded", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show()
contentTextView.text = ""
}
} catch (e: IOException) {
Toast.makeText(this, "Error loading file", Toast.LENGTH_SHORT).show()
}
}
}
}This app uses Android internal storage to save and load a simple text file named myfile.txt.
When the user taps Save, the app writes the text from the input field to the file using openFileOutput with MODE_PRIVATE, which means only this app can access the file.
When the user taps Load, the app checks if the file exists in the internal files directory, reads its content as text, and shows it in the TextView below.
Toast messages inform the user about success or errors during file operations.
This approach keeps file access simple and secure inside the app's private storage.