在Android开发过程中,经常会遇到需要创建txt文件并写入数据的情况。今天我们来介绍一下如何实现这样的功能。 一、创建txt文件 private void createFile() { //传入路径 + 文件名
在Android开发过程中,经常会遇到需要创建txt文件并写入数据的情况。今天我们来介绍一下如何实现这样的功能。
private void createFile() { //传入路径 + 文件名 File mFile = new File(mStrPath); //判断文件是否存在,存在就删除 if (mFile.exists()) { mFile.delete(); } try { //创建文件 mFile.createNewFile(); Log.i("文件创建", "文件创建成功"); } catch (ioException e) { e.printStackTrace(); } }
代码中的mStrPath为txt文件存储的路径,根据个人的需求确定路径,此处以 根目录,并命名为transcript.txt 为例,即
mStrPath = Environment.getExternalStorageDirectory().getPath() + "/transcript.txt";
public void read(String fileName, Consumer lineValue) throws IOException { File file = new File(fileName); InputStreamReader inputStreamReader = null; BufferedReader br = null; try { if (!file.exists()){ throw new FileNotFoundException("未找到文件:".concat(fileName)); } inputStreamReader = new InputStreamReader(new FileInputStream(file)); br = new BufferedReader(inputStreamReader); String line; while (null != (line = br.readLine())){ if (!"".equals(line)){ lineValue.accept(line); } } }finally { if (null != br){ br.close(); } if (null != inputStreamReader){ inputStreamReader.close(); } } }
public static void writeTxt(String fileName, String content) { try { //要指定编码方式,否则会出现乱码 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName, true),"gbk"); osw.write(content); osw.close(); } catch (IOException e) { e.printStackTrace(); } }
[注]:
①当FileOutputStream中的append参数为true时,表示向txt文件追加写入数据,反之,将清空原来数据写入新数据。
②当向txt文件写入中文字符时,建议使用“gbk”编码方式,否则容易出现乱码。
来源地址:https://blog.csdn.net/weixin_43230707/article/details/128599475
--结束END--
本文标题: Android开发创建txt文件并读写txt文件数据
本文链接: https://www.lsjlt.com/news/372692.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0