I want to read and write a file in the phone's external memory, but using the following code, I can only read and write in the phone's memory. And with the available functions, you can only access the address of the phone's memory I would be grateful if someone could help
class MainActivity : AppCompatActivity() {
private val STORAGE_PERMISSION_CODE = 1
private val filename = "SampleFile.txt"
private val filepath = "MyFileStorage"
var myExternalFile: File? = null
var sdexternal : String?=null
val context: Context =this
@RequiresApi(Build.VERSION_CODES.R)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// val sdCardState = Environment.getExternalStorageState()
// if (sdCardState == Environment.MEDIA_MOUNTED) {
// println("SD card is mounted and writable")
// } else if (sdCardState == Environment.MEDIA_MOUNTED_READ_ONLY) {
// println("SD card is mounted but read-only")
// } else {
// println("SD card is not mounted")
// }
///////////////////////////////////////////////
val readPermission = Manifest.permission.READ_EXTERNAL_STORAGE
val writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE
if (ContextCompat.checkSelfPermission(this, readPermission) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, writePermission) == PackageManager.PERMISSION_GRANTED) {
// Permissions already granted, proceed with accessing external storage
accessExternalStorage()
} else {
// Request permissions at runtime
ActivityCompat.requestPermissions(this, arrayOf(readPermission, writePermission), STORAGE_PERMISSION_CODE)
}
////////////////////////////////////////////////////
// val filename="file5111.txt"
// val sdCardRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
// //val sd= Environment.getExternalStorageState()
// //val sdCardRoot = Environment.getExternalStorageDirectory()
// //
// //val filePath = "storage/emulated/1/file" // Replace with the actual path to your text file
// val filePath = "$sdCardRoot" //FOR ROOT- COMMAND MAIN
//
// // val file = File(filePath)
// val file = File(filePath, filename)
//
// if (file.exists()) {
// val fileContent = readFromFile(file)
// println("File content: $fileContent")
// } else {
// println("File not found")
// createFile(file)
// println("File created: $filePath")
// }
}
private fun accessExternalStorage() {
val directoryType = Environment.DIRECTORY_DOCUMENTS
val externalFilesDir = context.getExternalFilesDir(directoryType)
val externalFilesDirPath = externalFilesDir?.absolutePath
println("External files directory path: $externalFilesDirPath")
// val externalStorageDirectory = Environment.getExternalStorageDirectory()
// val stat = StatFs(externalStorageDirectory.path)
//
// val blockSize = stat.blockSizeLong
// val totalBlocks = stat.blockCountLong
// val availableBlocks = stat.availableBlocksLong
//
// val totalSize = blockSize * totalBlocks
// val availableSize = blockSize * availableBlocks
//
// println("Total memory size: ${formatSize(totalSize)}")
// println("Available memory size: ${formatSize(availableSize)}")
val filename="file111.txt"
val sdCardRoot=externalFilesDirPath
//val sdCardRoot = File(Environment.getExternalStorageDirectory().absolutePath)
// val sdCardRoot = File(Environment.getExternalStorageDirectory().absolutePath,filename)
// val sdCardRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
// val file1 = File("$sdCardRoot") // Replace with the actual path to your file or directory
//
// val sizeInBytes = file1.length()
// val sizeInKilobytes = sizeInBytes / 1024
// val sizeInMegabytes = sizeInKilobytes / 1024
// val sizeInGigabytes = sizeInMegabytes / 1024
//
// println("Size: $sizeInBytes bytes, $sizeInKilobytes KB, $sizeInMegabytes MB, $sizeInGigabytes GB")
//val sd= Environment.getExternalStorageState()
// val sdCardRoot = Environment.getExternalStorageDirectory()
//
//val filePath = "storage/emulated/1/file" // Replace with the actual path to your text file
val filePath = "$sdCardRoot/reza/" //FOR ROOT- COMMAND MAIN
//val filePath="/sdcard"
// val file = File(filePath)
val file = File(filePath, filename)
if (file.exists()) {
val fileContent = readFromFile(file)
println("File content: $fileContent")
} else {
println("File not found")
createFile(file)
println("File created: $filePath")
}
}
private fun readFromFile(file: File): String {
val reader = FileReader(file)
val stringBuilder = StringBuilder()
val buffer = CharArray(4096)
var charsRead: Int
try {
while (reader.read(buffer).also { charsRead = it } != -1) {
stringBuilder.append(buffer, 0, charsRead)
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
reader.close()
}
return stringBuilder.toString()
}
fun createFile(file: File) {
try {
file.parentFile?.mkdirs()
file.createNewFile()
val writer = FileWriter(file)
writer.write("This is a new file.")
writer.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// Permissions granted, proceed with accessing external storage
//accessExternalStorage()
} else {
// Permissions denied, handle accordingly
}
}
}
private fun formatSize(size: Long): String {
val units = arrayOf("B", "KB", "MB", "GB", "TB")
var fileSize = size.toDouble()
var unitIndex = 0
while (fileSize > 1024 && unitIndex < units.size - 1) {
fileSize /= 1024
unitIndex++
}
return String.format("%.2f %s", fileSize, units[unitIndex])
}
private fun isExternalStorageReadOnly(): Boolean {
val extStorageState = Environment.getExternalStorageState()
return Environment.MEDIA_MOUNTED_READ_ONLY == extStorageState
}
private fun isExternalStorageAvailable(): Boolean {
val extStorageState = Environment.getExternalStorageState()
return Environment.MEDIA_MOUNTED == extStorageState
}
} And I have used different codes which are commented in the code up and even some codes have been deleted