ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-07-07 14:01:45  阅读:157  来源: 互联网

标签:读取 filePath private fileName file new android txt String


用到了几行代码,随手记录分享一下,动态手动输入文件名新建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:下载地址:戳一戳

标签:读取,filePath,private,fileName,file,new,android,txt,String
来源: https://blog.51cto.com/u_14397532/3000601

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有