【android studio】创建指定1k的文件,对其进行读写验证,出错则弹窗提醒
点击按钮在安装包路径循环创建以时间命名的文件,写入1k的全为1的数据,读取文件,对比读写是否一致,一致则pass删除文件,出错则弹窗提醒退出。
package com.example.newfile
//mitac-bu-
import android.content.DialogInterface
import android.os.Bundle
import android.os.Process
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
private var path: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
while (true) {
val fos: FileOutputStream
val all = IntArray(1024)
for (i in 0..1023) {
all[i] = 1;
}
var str = ""
for (i in 0..1023) {
str += all.get(i).toString()
}
val date = Date()
val timeTemp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(date.time)
path = getExternalFilesDir("")!!.absolutePath
val file = File(path + File.separator + timeTemp + ".txt")
try {
fos = FileOutputStream(file)
fos.write(str.toByteArray())
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
Thread.sleep(1000);
var content = ""
try {
val fis = FileInputStream(file)
val buffer = ByteArray(fis.available())
fis.read(buffer)
content = String(buffer)
fis.close()
} catch (e: Exception) {
e.printStackTrace()
}
if (str == content) {
Toast.makeText(this@MainActivity, "pass", Toast.LENGTH_SHORT).show()
Thread.sleep(1000);
file.delete();
Thread.sleep(1000);
} else {
val alertdialogbuilder = AlertDialog.Builder(this@MainActivity)
alertdialogbuilder.setMessage("WARNING!!!!")
alertdialogbuilder.setPositiveButton("确定", click1)
alertdialogbuilder.setNegativeButton("取消", click2)
val alertdialog1: AlertDialog = alertdialogbuilder.create()
alertdialog1.show()
}
}
}
}
private val click1 = DialogInterface.OnClickListener { arg0, arg1 -> Process.killProcess(Process.myPid()) }
private val click2 = DialogInterface.OnClickListener { arg0, arg1 -> arg0.cancel() }
}
通过pass
安装包路径
弹窗提醒