android逐行写入读取

Android external storage can be used to write and save data, read configuration files etc. This article is continuation of the Android Internal Storage tutorial in the series of tutorials on structured data storage in android.

Android外部存储可用于写入和保存数据,读取配置文件等。本文是有关Android内部结构化数据存储的系列教程中Android内部存储教程的继续。

Android外部存储 (Android External Storage)

External storage such as SD card can also store application data, there’s no security enforced upon files you save to the external storage.
In general there are two types of External Storage:

SD卡等外部存储设备也可以存储应用程序数据,保存到外部存储设备的文件没有安全性要求。
通常,外部存储有两种类型:

  • Primary External Storage: In built shared storage which is “accessible by the user by plugging in a USB cable and mounting it as a drive on a host computer”. Example: When we say Nexus 5 32 GB.主要外部存储设备 :内置的共享存储设备,“用户可以通过插入USB电缆并将其作为驱动器安装在主机上进行访问”。 示例:当我们说Nexus 5 32 GB时。
  • Secondary External Storage: Removable storage. Example: SD Card辅助外部存储 :可移动存储。 示例:SD卡

All applications can read and write files placed on the external storage and the user can remove them. We need to check if the SD card is available and if we can write to it. Once we’ve checked that the external storage is available only then we can write to it else the save button would be disabled.

所有应用程序都可以读写放置在外部存储器上的文件,并且用户可以删除它们。 我们需要检查SD卡是否可用以及是否可以对其进行写入。 一旦检查完外部存储仅可用,就可以对其进行写入,否则将禁用保存按钮。

Android外部存储示例项目结构 (Android External Storage Example Project Structure)

Firstly, we need to make sure that the application has permission to read and write data to the users SD card, so lets open up the AndroidManifest.xml and add the following permissions:

首先,我们需要确保该应用程序具有读取和写入用户SD卡数据的权限,因此让我们打开AndroidManifest.xml并添加以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Also, external storage may be tied up by the user having mounted it as a USB storage device. So we need to check if the external storage is available and is not read only.

另外,外部存储设备可能已被用户安装为USB存储设备而被捆绑。 因此,我们需要检查外部存储是否可用并且不是只读的。

if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {  saveButton.setEnabled(false);}  private static boolean isExternalStorageReadOnly() {  String extStorageState = Environment.getExternalStorageState();  if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  return true;  }  return false;  }  private static boolean isExternalStorageAvailable() {  String extStorageState = Environment.getExternalStorageState();  if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  return true;  }  return false;  }

getExternalStorageState() is a static method of Environment to determine if external storage is presently available or not. As you can see if the condition is false we’ve disabled the save button.

getExternalStorageState()Environment的静态方法,用于确定外部存储设备当前是否可用。 如您所见,如果条件为假,我们禁用了保存按钮。

Android外部存储示例代码 (Android External Storage Example Code)

The activity_main.xml layout is defined as follows:

activity_main.xml布局定义如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"android:layout_width="fill_parent" android:layout_height="fill_parent"android:orientation="vertical"><TextView android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Reading and Writing to External Storage"android:textSize="24sp"/><EditText android:id="@+id/myInputText"android:layout_width="match_parent"android:layout_height="wrap_content"android:ems="10" android:lines="5"android:minLines="3" android:gravity="top|left"android:inputType="textMultiLine"><requestFocus /></EditText><LinearLayoutandroid:layout_width="match_parent" android:layout_height="wrap_content"android:orientation="horizontal"android:weightSum="1.0"android:layout_marginTop="20dp"><Button android:id="@+id/saveExternalStorage"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="SAVE"android:layout_weight="0.5"/><Button android:id="@+id/getExternalStorage"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="0.5"android:text="READ" /></LinearLayout><TextView android:id="@+id/response"android:layout_width="wrap_content"android:layout_height="wrap_content" android:padding="5dp"android:text=""android:textAppearance="?android:attr/textAppearanceMedium" /></LinearLayout>

Here apart from the save and read from external storage buttons we display the response of saving/reading to/from an external storage in a textview unlike in the previous tutorial where android toast was displayed.

在这里,除了“保存和从外部存储读取”按钮外,我们还在文本视图中显示保存/读取/从外部存储读取的响应,这与之前显示android toast的教程不同。

The MainActivity.java class is given below:

MainActivity.java类如下所示:

package com.journaldev.externalstorage;import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;public class MainActivity extends Activity {EditText inputText;TextView response;Button saveButton,readButton;private String filename = "SampleFile.txt";private String filepath = "MyFileStorage";File myExternalFile;String myData = "";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);inputText = (EditText) findViewById(R.id.myInputText);response = (TextView) findViewById(R.id.response);saveButton =(Button) findViewById(R.id.saveExternalStorage);saveButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {try {FileOutputStream fos = new FileOutputStream(myExternalFile);fos.write(inputText.getText().toString().getBytes());fos.close();} catch (IOException e) {e.printStackTrace();}inputText.setText("");response.setText("SampleFile.txt saved to External Storage...");}});readButton = (Button) findViewById(R.id.getExternalStorage);readButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {try {FileInputStream fis = new FileInputStream(myExternalFile);DataInputStream in = new DataInputStream(fis);BufferedReader br =new BufferedReader(new InputStreamReader(in));String strLine;while ((strLine = br.readLine()) != null) {myData = myData + strLine;}in.close();} catch (IOException e) {e.printStackTrace();}inputText.setText(myData);response.setText("SampleFile.txt data retrieved from Internal Storage...");}});if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {saveButton.setEnabled(false);}else {myExternalFile = new File(getExternalFilesDir(filepath), filename);}}private static boolean isExternalStorageReadOnly() {String extStorageState = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {return true;}return false;}private static boolean isExternalStorageAvailable() {String extStorageState = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {return true;}return false;}}
  1. Environment.getExternalStorageState(): returns path to internal SD mount point like “/mnt/sdcard”Environment.getExternalStorageState() :返回到内部SD安装点的路径,例如“ / mnt / sdcard”
  2. getExternalFilesDir(): It returns the path to files folder inside Android/data/data/application_package/ on the SD card. It is used to store any required files for your app (like images downloaded from web or cache files). Once the app is uninstalled, any data stored in this folder is gone too.getExternalFilesDir() :它返回SD卡上Android / data / data / application_package /中的files文件夹的路径。 它用于存储应用程序所需的任何文件(例如从Web下载的图像或缓存文件)。 卸载应用后,该文件夹中存储的所有数据也将消失。

Also if the external storage is not available we disable the save button using the if condition that was discussed earlier in this tutorial.

另外,如果外部存储不可用,我们将使用本教程前面讨论的if条件禁用保存按钮。

Below is our application running in android emulator, where we are writing data to file and then reading it.

下面是我们在android模拟器中运行的应用程序,我们在其中将数据写入文件,然后读取它。

Note: Make sure your Android Emulator is configured such that it has a SD card as shown in the image dialog from AVD below. Go to Tools->Android->Android Virtual Device, edit configurations->Show Advance Settings.

注意:请确保您的Android仿真器已配置为具有SD卡,如下面AVD中的图像对话框所示。 转到工具-> Android-> Android虚拟设备,编辑配置->显示高级设置。

This brings an end to this tutorial. We’ll discuss storage using Shared Preferences in the next tutorial. You can download the final Android External Storage Project from the below link.

本教程到此结束。 在下一个教程中,我们将使用“共享首选项”讨论存储。 您可以从下面的链接下载最终的Android外部存储项目。

Download Android External Storage Example Project下载Android外部存储示例项目

翻译自: https://www.journaldev.com/9400/android-external-storage-read-write-save-file

android逐行写入读取

android逐行写入读取_Android外部存储-读取,写入,保存文件相关推荐

  1. Android学习笔记-判断手机外部存储是否可读写

    通过调用Environment的getExternalStorageState()方法来判断外部存储的状态: /* 查检外部存储读取与写入功能是否可用 */ public boolean isExte ...

  2. 【Android取证篇】华为外部存储支持备份的数据类型-支持第三方应用

    [Android取证篇]华为外部存储支持备份的数据类型-支持第三方应用 ​ 数据保存至外置存储卡或USB存储,"无需网络连接"!,支持部分第三方应用的数据备份-[suy] 文章目录 ...

  3. android 存储无法写入,在Android中的外部存储中写入文件

    我想在外部存储sdCard中创建一个文件并写入它.我已经通过互联网搜索并尝试但没有得到结果,我已经在Android Manifest文件中添加了权限,我在模拟器上这样做,我正在尝试下面的代码和获取ER ...

  4. 电脑看不到android文件夹,电脑无法查看安卓手机外部存储(emulated)文件原因及解决方法...

    电脑无法查看安卓手机外部存储(emulated)文件原因及解决方法 eonegh • 2019 年 09 月 07 日 从安卓端传输图片,CSV,TXT等文件到电脑端时就会经常出现无法显示问题(这里是 ...

  5. Android 11 高版本 出现外部存储无法访问的问题

    最近在做Android 应用开发,IDE是android studio , 使用的版本配置如下:compileSdk 32 buildToolsVersion '32.0.0' defaultConf ...

  6. android 外部存储列表,如何获取Android设备的已安装外部存储列表

    我使用/ proc / mounts文件来获取可用存储选项的列表 public class StorageUtils { private static final String TAG = " ...

  7. android指定sqlite路径_android sqlite 存储位置

    Android 开发中使用 SQLite 数据库 SQLite 是一款非常流行的嵌入式数据库,它支持 SQL 查询,并且只用很少的内存.Android 在运行时集成了 SQLite,所以每个 Andr ...

  8. android activity启动模式_Android知识点【Activity】清单文件

    哈喽 好久不见,最近太忙了 请大家原谅 今天我们来说一下android清单文件Activity都有哪些配置,来先上图: 大家一下子看了这么多属性可能觉得有些懵逼,我这边也是就常用的一些数据给大家做一下 ...

  9. Android中使用又拍云存储来上传文件(包括图片、音频和视频等)

    资料: 在又拍云存储上申请账号,然后购买一定的空间.(具体可上它的官网详细了解) 原理: 又拍云存储说白了就是一个中介.客户端把所需要上传的东西传到又拍云端服务器,云端服务器在通知到我们自己创建的服务 ...

最新文章

  1. 计算机二级是立刻知道成绩单,可以在公布前知道计算机二级考成绩吗
  2. 与孩子一起学编程 python_【和孩子一起学编程】 python笔记--第五天
  3. C# access update 出错总结,注意事项
  4. python 使用 requests 做 http 请求
  5. rails jquery_Spring与Rails的jQuery UJS
  6. hdfs java 权限管理,HDFS的权限管理
  7. [转][C#] .net动态编译C# 和 VB
  8. 使用HttpClient连接池进行https单双向验证
  9. 【UG NX MCD 机电一体化概念设计】UG NX MCD+PLCSIM Advanced联合仿真实例(二 )仿真序列
  10. linux制作虚拟机镜像,为OpenStack制作CoreOS虚拟机镜像(基于CoreOS官方提供镜像)
  11. android ionic框架,移动App开发框架—Ionic
  12. TeeChart曲线平滑 Line.Smoothed
  13. 向量叉积和点积混合运算_叉乘点乘混合运算公式
  14. 知识兔课程揭秘2021抖音卖货代运营的新骗局,你中招了吗?
  15. 数据投毒攻防对抗技术-2.推荐系统中的数据投毒
  16. 谷歌浏览器播放器声音
  17. iOS-获取健康运动步数
  18. Centos系统找出并杀死僵尸进程
  19. 高斯求和问题(C语言程序设计)
  20. Openstack的安装部署教程

热门文章

  1. 使用jquery实现局部刷新DIV
  2. asp.net 导出word文档
  3. 强名称(3)强名称的脆弱性
  4. [原]批量生成AWR报告
  5. saltstack 远程执行之返回写入到mysql
  6. 裴蜀(贝祖)定理及其证明
  7. 第三十一篇 玩转数据结构——并查集(Union Find)
  8. MYSQL—— 启动MYSQL 57 报错“The service MYSQL57 failed the most recent........等”的问题解决方式!...
  9. 华为机试题2[编程题] 汽水瓶
  10. 一位信息系统项目管理培训老师写的《论婚姻项目管理》值得看一下!