【android studio】创建指定1M的文件,对其进行读写验证,出错则弹窗提醒

发现之前写的创建1k的那个程序,如果我想创建1M的文件则会出现问题。于是研究修改了一下。这次使用了线程的方式,以及使用RandomAccessFile方法创建文件,创建指定1M的文件,写入全为1的内容,并进行读写验证,出错则弹窗提醒。

package com.example.f4
//mitac-bu-
import android.content.DialogInterface
import android.os.Bundle
import android.os.Handler
import android.os.Process
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import java.nio.MappedByteBuffer
import java.nio.channels.FileChannel
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {
    var button: Button? = null
    val myhandle = Handler()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById(R.id.buttonProgressBar)
        button!!.setOnClickListener(buttonListener())
    }

    internal inner class buttonListener : View.OnClickListener {
        override fun onClick(v: View) {
            println("Start UpdateThread!")
            myhandle.post(UpdateThread);
        }
    }

    var UpdateThread: Runnable = object : Runnable {
        private var path: String? = null
        val length = 1048576;
        override fun run() {
            println("--updateThread--")
                val date = Date()
                val timeTemp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(date.time)
                path = getExternalFilesDir("")!!.absolutePath
                val file = File(path + File.separator + timeTemp + ".txt")
                try {

                    val fc: FileChannel = RandomAccessFile(file, "rw").getChannel()
                    val out: MappedByteBuffer = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1048576);
                    for (i in 0 until length) {
                        out.put('1'.toByte())
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                val raf = RandomAccessFile(file, "rw")
                raf.seek(0)
                while (raf.read()!= -1) {
                    if(raf.read() != 49) {
                        val alertdialogbuilder = AlertDialog.Builder(this@MainActivity)
                        alertdialogbuilder.setMessage("执行结束是否退出")
                        alertdialogbuilder.setPositiveButton("确定", click1)
                        alertdialogbuilder.setNegativeButton("取消", click2)
                        val alertdialog1: AlertDialog = alertdialogbuilder.create()
                        alertdialog1.show()
                        Thread.sleep(10000);
                    }
                }
                raf.close()
                file.delete()
                if(!file.exists()) {
                    println("++file delect++")
                }
            myhandle.postDelayed(this, 1000)
        }
        private val click1 = DialogInterface.OnClickListener { arg0, arg1 -> Process.killProcess(Process.myPid()) }
        private val click2 = DialogInterface.OnClickListener { arg0, arg1 -> arg0.cancel() }
    }
}

package com.mitac.mmcteststress;
import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Random;



public class MainActivity extends AppCompatActivity {
    private static String TAG = "StorageThread";
    private Context context;
    private String sTestResult = "";
    private TextView sTextView1;
    private TextView sTextView2;
    private TextView sTextView3;
    private ScrollView sScrollView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sTextView1 = (TextView) findViewById(R.id.reltitle);
        sTextView3 = (TextView) findViewById(R.id.rellog);
        sScrollView = (ScrollView) findViewById(R.id.sscrollView1);

        StorageRelThread t = new StorageRelThread(this);
        t.start();

    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.arg1 == 1) {
                sTestResult += (String) msg.obj + "\n";
                sTextView3.setText(sTestResult);
                sScrollView.scrollTo(0, sTestResult.length());
                if (sTextView3.getText().length() > 10000) {
                    sTestResult = "";
                }
            } else if (msg.arg1 == 2) {
                sTestResult += (String) msg.obj + "\n";
                sTextView3.setText(sTestResult);
                sScrollView.scrollTo(0, sTestResult.length());
                if (sTextView3.getText().length() > 10000) {
                    sTestResult = "";
                }
            }
        }
    };

    void SendMyMessage(Handler msghandler, int type, String msg) {
        Message MSG = msghandler.obtainMessage();
        MSG.obj = msg;
        MSG.arg1 = type;
        msghandler.sendMessage(MSG);
    }

    public class StorageRelThread extends Thread {
        StorageRelThread(Context c) {
            context = c;
        }

        private String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        private Random random;
        private char bufW[];
        private char bufR[];
        private FileWriter fileW;
        private FileReader fileR;
        private int Currentcycle = 0;

        @Override
        public void run() {

            try {
                File baseDirectory = getExternalFilesDir("");
                random = new Random();
                int fileSize = 10 * 1024 * 1024;
                bufW = new char[fileSize];
                for (int i = 0; i < fileSize; ++i) {
                    int number = random.nextInt(62);
                    bufW[i] = str.charAt(number);
                }

                Currentcycle = 0;
                while (true) {
                    Currentcycle++;
                    SendMyMessage(handler, 2, "\n#############Cycle:" + Currentcycle + "#############");
                    SendMyMessage(handler, 2, "====Begin writing==== ");
                    for (int i = 0; i < 10; ++i) {
                        String writeFilename = "SD_Reliability_test_" + Integer.toString(i + 1) + ".data";
                        fileW = new FileWriter(baseDirectory + "/" + writeFilename);
                        fileW.write(bufW);
                        fileW.close();
                    }
                    SendMyMessage(handler, 2, "====Begin reading==== ");
                    for (int i = 0; i < 10; ++i) {
                        String writeFilename = "SD_Reliability_test_" + Integer.toString(i + 1) + ".data";
                        bufR = new char[fileSize + 10];
                        fileR = new FileReader(baseDirectory +  "/" + writeFilename);
                        int iRead = fileR.read(bufR);
                        fileR.close();
                        if (iRead != fileSize) {
                            SendMyMessage(handler, 2, "The length of file " + Integer.toString(i + 1) + " isn't correct.");
                        } else {
                            SendMyMessage(handler, 2, "The length of file " + Integer.toString(i + 1) + " is correct.");
                        }
                        boolean bSame = true;
                        for (int j = 0; j < fileSize; ++j) {
                            if (bufR[j] != bufW[j]) {
                                bSame = false;
                            }
                        }
                        if (bSame) {
                            SendMyMessage(handler, 2, "The file content " + Integer.toString(i + 1) + " is correct.");
                        } else {
                            SendMyMessage(handler, 2, "The file content " + Integer.toString(i + 1) + " isn't correct.");
                        }
                    }

                    File folder = new File(baseDirectory +  "/" );
                    File[] files = folder.listFiles();
                    for (int i=0; i<files.length; i++) {
                        File file = files[i];
                        file.delete();
                    }
                }


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值