android之动态新建txt文件与读取

版权声明:本文为博主原创文章,遵循 CC 4.0 BY 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/generallizhong/article/details/100150849

用到了几行代码,随手记录分享一下,动态手动输入文件名新建txt与存入的内容到txt文件,并且读取出来了,在文章最后附上DEMO

一、看一下简单demo效果图

二、接下里直接看代码了,

主界面代码:

public class MainActivity extends Activity implements OnClickListener {

    private EditText mPathName;
    private EditText mFileName;
    private EditText mContent;
    private Button mTest;
    private Button mBtnRead;
    private TextView mShowTet;
    String filePath;
    String fileName1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findid();

    }

    private void findid() {
        mPathName = (EditText) findViewById(R.id.et_pathName);
        mFileName = (EditText) findViewById(R.id.et_fileName);
        mContent = (EditText) findViewById(R.id.et_content);
        mTest = (Button) findViewById(R.id.btn_test);

        mBtnRead = (Button) findViewById(R.id.btn_read);
        mShowTet = (TextView) findViewById(R.id.Show_tet);
        mTest.setOnClickListener(this);
        mBtnRead.setOnClickListener(this);
    }

    private void getcontent() {
        //动态创建文件
        String pathName = mPathName.getText().toString();
        String fileName = mFileName.getText().toString();
        String content = mContent.getText().toString();
        if (TextUtils.isEmpty(pathName)) {
            Toast.makeText(this, "文件夹名不能为空", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(fileName)) {
            Toast.makeText(this, "文件名不能为空", Toast.LENGTH_SHORT).show();
        } else {
            Tool tool = new Tool();
            filePath = Environment.getExternalStorageDirectory()
                    .getPath() + "/" + pathName + "/";
            fileName1 = fileName + ".txt";

            tool.writeTxtToFile(content, filePath, fileName1);// 将字符串写入到文本文件中
            Toast.makeText(this, "创建成功", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_test:
                getcontent();
                break;
            case R.id.btn_read:
                Tool tool = new Tool();
//storage/emulated/0/z/z1.txt   地址也可添加为固定   filePath+fileName1  动态地址
                mShowTet.setText(tool.readTxt("storage/emulated/0/z/z1.txt"));

                break;
        }
    }

}

三、其次就是主要的新建文件与存入文字、读取文字的工具类代码


/**
 * 工具类
 *
 * @author gph
 */
public class Tool {

    /**
     * 将字符串写入到文本文件中
     */
    public void writeTxtToFile(String strcontent, String filePath,
                               String fileName) {
        // 生成文件夹之后,再生成文件,不然会出错
        makeFilePath(filePath, fileName);// 生成文件

        String strFilePath = filePath + fileName;
        // 每次写入时,都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("error:", e + "");
        }
    }

    /**
     * 生成文件
     */
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);// 生成文件夹
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 生成文件夹
     */
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

    public String readTxt(String file) {
        Log.e("LZ:", file);
        BufferedReader bre = null;
        String str = "";
        String returnstr = "";
        String a;
        try {

            bre = new BufferedReader(new FileReader(file));//此时获取到的bre就是整个文件的缓存流
            while ((str = bre.readLine()) != null) { // 判断最后一行不存在,为空结束循环

                Log.e("LZ", "readTxt: a------------" + str);

                String[] arr = str.split("\\s+");
                for (String ss : arr) {
                    a = arr[0];
                }

                Log.e("LZ-----str:", str);
                returnstr=str;
            }

        } catch (Exception e) {
            Log.e("LZ", "readTxt: ---------------" + e.toString());
        }
        return returnstr;
    }

}

逻辑代码全部已贴,如需要demo请戳下面

github下载地址:戳一下

CSDN:下载地址:戳一戳

猜你喜欢

转载自blog.csdn.net/generallizhong/article/details/100150849
今日推荐