当前位置: 首页 > news >正文

android studio 读写文件操作(应用场景二)

android studio版本:2023.3.1 patch2

例程:readtextviewIDsaveandread

本例程是个过渡例程,如果单是实现下图的目的有更简单的方法,但这个方法是下一步工作的基础,所以一定要做。

例程功能:将两个textview的text保存到文件,再通过一个按钮读出文件内容,并将两个值分别赋值给另两个textview的text.实现修改多个textview的text的目的。

例程演示:

代码:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextViewandroid:id="@+id/textView2"android:layout_width="150dp"android:layout_height="35dp"android:background="#00BCD4"android:text="Hello World!"android:textSize="24dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.498"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textView1"app:layout_constraintVertical_bias="0.099" /><TextViewandroid:id="@+id/textView1"android:layout_width="110dp"android:layout_height="35dp"android:layout_marginTop="288dp"android:background="#00BCD4"android:text="演示内容"android:textSize="24dp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.498"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="104dp"android:layout_marginTop="48dp"android:text="存储"android:textSize="20dp"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textView3" /><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="48dp"android:layout_marginTop="4dp"android:text="读取"android:textSize="20dp"app:layout_constraintStart_toEndOf="@+id/button1"app:layout_constraintTop_toTopOf="@+id/button1" /><TextViewandroid:id="@+id/textView3"android:layout_width="150dp"android:layout_height="35dp"android:layout_marginStart="68dp"android:layout_marginTop="48dp"android:text="TextView"android:textSize="24dp"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textView2" /><TextViewandroid:id="@+id/textView4"android:layout_width="140dp"android:layout_height="35dp"android:layout_marginStart="32dp"android:text="TextView"android:textSize="24dp"app:layout_constraintStart_toEndOf="@+id/textView3"app:layout_constraintTop_toTopOf="@+id/textView3" /></androidx.constraintlayout.widget.ConstraintLayout>

由于“写文件”还是用到了前一篇(android studio 读写文件操作(方法一)(转)-CSDN博客)的方法,所以保留了相关内容,其实不用也行,懒得改。

FileHelper.java

package com.shudu.readtextviewidsaveandread;import android.content.Context;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class FileHelper {private Context mContext;public FileHelper() {}public FileHelper(Context mContext) {super();this.mContext = mContext;}/** 这里定义的是一个文件保存的方法,写入到文件中,所以是输出流* */public void save(String filename, String filecontent) throws Exception {//这里我们使用私有模式,创建出来的文件只能被本应用访问,还会覆盖原文件哦FileOutputStream output = mContext.openFileOutput(filename, Context.MODE_PRIVATE);output.write(filecontent.getBytes());  //将String字符串以字节流的形式写入到输出流中output.close();         //关闭输出流}/** 这里定义的是文件读取的方法* */public String read(String filename) throws IOException {//打开文件输入流FileInputStream input = mContext.openFileInput(filename);byte[] temp = new byte[1024];StringBuilder sb = new StringBuilder("");int len = 0;//读取文件内容:while ((len = input.read(temp)) > 0) {sb.append(new String(temp, 0, len));}//关闭输入流input.close();return sb.toString();}}

mainactivity.java

package com.shudu.readtextviewidsaveandread;import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private TextView textview1,textview2,textview3,textview4;private Button button1,button2;private Context mContext;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);mContext = getApplicationContext();//string的上下文对象,我也不知道是啥,没它不行。ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});textview1=(TextView)findViewById(R.id.textView1);textview2 = (TextView) findViewById(R.id.textView2);textview3 = (TextView) findViewById(R.id.textView3);textview4 = (TextView) findViewById(R.id.textView4);button1 = (Button) findViewById(R.id.button1);button2 = (Button) findViewById(R.id.button2);button1.setOnClickListener(this);button2.setOnClickListener(this);}public void onClick(View view) {switch (view.getId()){case R.id.button1://写FileHelper fHelper = new FileHelper(mContext);String filename = "10000.txt";String filedetail = textview1.getText().toString();String filedetail1= textview2.getText().toString();String newstring=filedetail+","+filedetail1;try {fHelper.save(filename, newstring);System.out.println("文件名为:"+filename);Toast.makeText(getApplicationContext(), "数据写入成功", Toast.LENGTH_SHORT).show();} catch (Exception e) {e.printStackTrace();Toast.makeText(getApplicationContext(), "数据写入失败", Toast.LENGTH_SHORT).show();}break;case R.id.button2://读//FileHelper fHelper2 = new FileHelper(getApplicationContext());readFileAndSplit();break;}}@Overridepublic void onPointerCaptureChanged(boolean hasCapture) {}private void readFileAndSplit(){File file =new File(getFilesDir(),"10000.txt");//这个必须单独写,不能直接写到try里面,不知道为啥。try(BufferedReader reader=new BufferedReader(new FileReader(file))){String line=reader.readLine();//读取行String[] parts=line.split(",");//split按照“,”分割,并写进part1数组String str1=parts[0].trim();//读数组第一个值,trim是去年后面空格。String str2=parts[1].trim();//读数组第二个值textview3.setText(str1);textview4.setText(str2);} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}}
}

 中间保存文件位置参照前一篇(方法一)。

有关this,switch的R.id错误,参照android studio 按钮点击事件的实现方法(三种方法)_安卓按钮点击事件-CSDN博客

相关内容修改。

相关文章:

android studio 读写文件操作(应用场景二)

android studio版本&#xff1a;2023.3.1 patch2 例程&#xff1a;readtextviewIDsaveandread 本例程是个过渡例程&#xff0c;如果单是实现下图的目的有更简单的方法&#xff0c;但这个方法是下一步工作的基础&#xff0c;所以一定要做。 例程功能&#xff1a;将两个textvi…...

小尺寸低功耗蓝牙模块在光伏清扫机器人上的应用

一、引言 随着可再生能源的迅速发展&#xff0c;光伏发电系统的清洁与维护变得越来越重要。光伏清扫机器人通过自动化技术提高了清洁效率&#xff0c;而蓝牙模组的集成为这些设备提供了更为智能的管理和控制方案。 二、蓝牙模组的功能与实现&#xff1a; 蓝牙模组ANS-BT103M…...

防火墙有什么作用

防火墙的作用&#xff1a;1. 提供网络安全防护&#xff1b;2. 实施访问控制和流量过滤&#xff1b;3. 检测和阻止恶意攻击&#xff1b;4. 保护内部网络免受未经授权的访问&#xff1b;5. 监控网络流量和安全事件&#xff1b;6. 支持虚拟专用网络&#xff08;VPN&#xff09;。防…...

MongoDB-BSON 协议与类型

前言&#xff1a; MongoDB 是一个高性能、无模式的 NoSQL 数据库&#xff0c;广泛应用于大数据处理和实时数据存储。作为一个数据库系统&#xff0c;MongoDB 的核心之一就是其使用的 BSON&#xff08;Binary JSON&#xff09;格式&#xff0c;它用于存储数据以及在客户端和数据…...

学习threejs,使用VideoTexture实现视频Video更新纹理

&#x1f468;‍⚕️ 主页&#xff1a; gis分享者 &#x1f468;‍⚕️ 感谢各位大佬 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍⚕️ 收录于专栏&#xff1a;threejs gis工程师 文章目录 一、&#x1f340;前言1.1 ☘️VideoTexture 视频纹理 二、…...

怎么获取键值对的键的数值?

问&#xff1a; 通过paelData.cardMap.C0002112可以获取到Cooo2112里面的数据&#xff0c;但是有时候接口返回的不是C0002112而是C0002093或者其他值&#xff0c;请问我该怎么写&#xff1f; 后端返回的数据是这样的&#xff1a; cardMap: { C0002112: { name: Item 1, va…...

数据结构排序算法详解

数据结构排序算法详解 1、冒泡排序&#xff08;Bubble Sort&#xff09;2、选择排序&#xff08;Selection Sort&#xff09;2、插入排序&#xff08;Insertion Sort&#xff09; 1、冒泡排序&#xff08;Bubble Sort&#xff09; 原理&#xff1a;越小的元素会慢慢“浮”到数…...

在Linux设置postgresql开机自启动,创建一个文件 postgresql-15.service

在Linux设置postgresql开机自启动&#xff0c;创建一个文件 postgresql-15.service 在Linux设置postgresql开机自启动&#xff0c;创建一个文件 postgresql-15.service1. 创建 systemd 服务文件2. 编辑服务文件3. 保存并退出4. 重新加载 systemd 配置5. 启动 PostgreSQL 服务6.…...

【kafka】消息队列的认识,Kafka与RabbitMQ的简单对比

什么是消息队列&#xff1f; 消息队列&#xff08;Message Queue&#xff0c;简称 MQ&#xff09;是一个在不同应用程序、系统或服务之间传递数据的机制。 它允许系统间异步地交换信息&#xff0c;而无需直接交互&#xff0c;确保消息的可靠传输。 想象一下&#xff0c;你正在…...

ProjectSend 身份认证绕过漏洞复现(CVE-2024-11680)

0x01 产品描述: ProjectSend 是一个开源文件共享网络应用程序,旨在促进服务器管理员和客户端之间的安全、私密文件传输。它是一款相当流行的应用程序,被更喜欢自托管解决方案而不是 Google Drive 和 Dropbox 等第三方服务的组织使用。0x02 漏洞描述: ProjectSend r1720 之前…...

Android笔记(三十四):onCreate执行Handler.post在onResume后才能执行?

背景 偶然发现一个点&#xff0c;就是在onCreate执行Handler.post在onResume后才执行&#xff0c;以下是测试代码 多次运行的结果一致&#xff0c;为什么execute runnable不是在onCreate和onResume之间执行的呢&#xff0c;带着疑问撸了一遍Activity启动流程 关键源码分析 …...

关闭模组的IP过滤功能

关闭模组的IP过滤功能 关闭模组的IP过滤功能 本脚本用于关闭模组的IP过滤功能&#xff0c;关闭后&#xff0c; 源地址不是终端IP的数据包&#xff0c;也可以被模组转发给网络 关闭模组的IP过滤功能 cat > /usr/bin/ipfilter << "EOF"echo -e "ATCFUN…...

算法分析与设计复习笔记

插入排序 1. void insert_sort(int A[ ],int n) 2. { 3. int a,i,j; 4. for (i1;i<n;i) { 5. a A[ i ]; 6. j i – 1; 7. while (j>0 && A[j]>a) { 8. A[ j…...

vue-amap 高德地图

vue-amap是一套基于Vue 2/vue3和高德地图的地图组件 vue-amap 高德地图2.0版本的对应vue3...

Numpy基础练习

import numpy as np 1.创建一个长度为10的一维全为0的ndarray对象,然后让第5个元素等于1 n np.zeros(10,dtypenp.int32) n[4] 12.创建一个元素从10到49的ndarray对象 n np.arrange(10,50)3.将第2题的所有元素位置反转 n[::-1]使用np.random.random创建一个10*10的ndarray对象…...

一番赏小程序定制开发,打造全新抽赏体验平台

随着盲盒的热潮来袭&#xff0c;作为传统的潮玩方式一番赏也再次受到了大家的关注&#xff0c;市场热度不断上升&#xff01; 一番赏能够让玩家百分百中奖&#xff0c;商品种类丰富、收藏价值高&#xff0c;拥有各种IP&#xff0c;从而吸引着各个圈子的粉丝玩家&#xff0c;用…...

【前端】将vue的方法挂载到window上供全局使用,也方便跟原生js做交互

【前端】将vue的方法挂载到window上供全局使用&#xff0c;也方便跟原生js做交互 <template><div><el-button click"start">调用方法</el-button></div> </template> <script> // import { JScallbackProc } from ./JScal…...

Oracle查询优化:高效实现仅查询前10条记录的方法与实践

在 Oracle 中&#xff0c;实现仅查询前10条记录的四种方法 1. 使用 ROWNUM 查询 ROWNUM 是 Oracle 中的伪列&#xff0c;用于限制返回的行数。 SELECT * FROM table_name WHERE condition AND ROWNUM < 10;condition&#xff1a;查询条件。ROWNUM < 10&#xff1a;限制…...

go语言编译问题

go编译 goproxy地址 阿里云 https://mirrors.aliyun.com/goproxy/七牛云 https://goproxy.cn/开源版 https://goproxy.io/nexus社区 https://gonexus.dev/启用 Go Modules 功能 go env -w GO111MODULEon配置 GOPROXY 环境变量&#xff0c;以下三选一 七牛 CDN go env -w …...

mobi文件转成pdf

将 MOBI 文件转换为 PDF 格式通常涉及两个步骤&#xff1a; 解析 MOBI 文件&#xff1a;需要提取 MOBI 文件的内容&#xff08;文本、图片等&#xff09;。将提取的内容转换为 PDF&#xff1a;将 MOBI 文件的内容渲染到 PDF 格式。 可用工具 kindleunpack 或 mobi&#xff1…...

英飞凌TC377芯片选型指南:从300MHz三核到FlexRay,汽车电子工程师如何快速上手?

英飞凌TC377芯片选型实战&#xff1a;汽车电子工程师的黄金法则 当汽车电子工程师面对英飞凌TC377这颗"三核300MHz怪兽"时&#xff0c;数据手册上密密麻麻的参数表格往往让人无从下手。我曾参与过某新能源车企的域控制器开发&#xff0c;团队花了整整两周时间争论芯片…...

手把手教你配置:用微型纵向加密搞定IEC-104协议的风光数据安全上传

新能源场站IEC-104协议安全传输实战&#xff1a;微型纵向加密配置全指南 在新能源场站的自动化系统中&#xff0c;IEC-104协议作为电力行业标准通信规约&#xff0c;承担着风机、光伏逆变器与升压站之间关键运行数据传输的重任。然而&#xff0c;传统光纤环网中的明文传输方式存…...

跨平台开发终极对决:uniapp、uniapp-X、React Native 与 Flutter 全面解析

作者&#xff1a;前端组件开发 发布日期&#xff1a;2026年2月20日 关键词&#xff1a;跨平台开发、uniapp、uniapp-X、React Native、Flutter、前端框架选型 在移动应用开发日益多元化的今天&#xff0c;如何在保证用户体验的同时提升开发效率&#xff0c;成为每个团队必须面对…...

Phi-4-mini-reasoning+ollama打造教育AI助手:中小学奥数题自动解析案例

Phi-4-mini-reasoningollama打造教育AI助手&#xff1a;中小学奥数题自动解析案例 1. 为什么需要教育AI助手&#xff1f; 中小学奥数题解析一直是家长和老师的痛点。传统方式需要专业老师一对一辅导&#xff0c;成本高且效率低。很多家长自己也不会解题&#xff0c;辅导孩子作…...

OpenClaw人人养虾:密钥管理

Gateway 提供安全的密钥管理&#xff08;Secrets Management&#xff09;功能&#xff0c;用于加密存储 API Key、Token 等敏感凭证&#xff0c;避免在配置文件中暴露明文。为什么需要密钥管理明文风险将 API Key 直接写在配置文件中存在严重安全风险&#xff1a;配置文件可能被…...

ViVe完整贡献指南:从入门到精通的开源参与秘籍

ViVe完整贡献指南&#xff1a;从入门到精通的开源参与秘籍 【免费下载链接】ViVe C# library and console app for using new feature control APIs available in Windows 10 version 2004 and newer 项目地址: https://gitcode.com/gh_mirrors/vi/ViVe ViVe是一个C#库&…...

Git-RSCLIP遥感图像分类参数详解:英文标签设计与置信度调优

Git-RSCLIP遥感图像分类参数详解&#xff1a;英文标签设计与置信度调优 1. 模型背景与核心能力 Git-RSCLIP 是北航团队基于 SigLIP 架构开发的遥感图像-文本检索模型&#xff0c;在 Git-10M 数据集&#xff08;1000万遥感图文对&#xff09;上完成大规模预训练。它不是传统意…...

实战指南:在Altera FPGA上配置AES256加密的完整流程与避坑要点

1. 为什么要在FPGA上配置AES256加密&#xff1f; 最近有个做工业控制的朋友找我吐槽&#xff0c;说他们竞争对手居然直接复制了他们的FPGA程序&#xff0c;改个LOGO就当成自己的产品卖。这种事情在嵌入式领域其实很常见&#xff0c;特别是使用Altera&#xff08;现在属于Intel&…...

如何用ViGEmBus实现Windows内核级游戏手柄模拟:架构解析与实践指南

如何用ViGEmBus实现Windows内核级游戏手柄模拟&#xff1a;架构解析与实践指南 【免费下载链接】ViGEmBus Windows kernel-mode driver emulating well-known USB game controllers. 项目地址: https://gitcode.com/gh_mirrors/vi/ViGEmBus ViGEmBus是一款Windows内核模…...

CPU内部总线架构解析:数据通路设计与性能优化

1. CPU内部总线架构概述 当你用手机玩游戏时&#xff0c;有没有想过为什么角色移动能如此流畅&#xff1f;这背后离不开CPU内部精密的数据高速公路——总线架构。就像城市交通网络决定了车辆通行效率&#xff0c;CPU内部总线结构直接影响着数据流动的速度和效率。 现代CPU内部主…...