Android 开发笔记___SD卡文件操作

时间:2022-04-21 13:16:15
 package com.example.alimjan.hello_world.Utils;

 import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Locale; public class FileUtil { public static void saveText(String path, String txt) {
try {
FileOutputStream fos = new FileOutputStream(path);
fos.write(txt.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
} public static String openText(String path) {
String readStr = "";
try {
FileInputStream fis = new FileInputStream(path);
byte[] b = new byte[fis.available()];
fis.read(b);
readStr = new String(b);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return readStr;
} public static void saveImage(String path, Bitmap bitmap) {
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
} public static Bitmap openImage(String path) {
Bitmap bitmap = null;
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
} public static ArrayList<File> getFileList(String path, String[] extendArray) {
ArrayList<File> displayedContent = new ArrayList<File>();
File[] files = null;
File directory = new File(path);
if (extendArray != null && extendArray.length>0) {
FilenameFilter fileFilter = getTypeFilter(extendArray);
files = directory.listFiles(fileFilter);
} else {
files = directory.listFiles();
} if (files != null) {
for (File f : files) {
if (!f.isDirectory() && !f.isHidden()) {
displayedContent.add(f);
}
}
}
return displayedContent;
} public static FilenameFilter getTypeFilter(String[] extendArray) {
final ArrayList<String> fileExtensions = new ArrayList<String>();
for (int i=0; i<extendArray.length; i++) {
fileExtensions.add(extendArray[i]);
}
FilenameFilter fileNameFilter = new FilenameFilter() {
@Override
public boolean accept(File directory, String fileName) {
boolean matched = false;
File f = new File(String.format("%s/%s",
directory.getAbsolutePath(), fileName));
matched = f.isDirectory();
if (!matched) {
for (String s : fileExtensions) {
s = String.format(".{0,}\\%s$", s);
s = s.toUpperCase(Locale.getDefault());
fileName = fileName.toUpperCase(Locale.getDefault());
matched = fileName.matches(s);
if (matched) {
break;
}
}
}
return matched;
}
};
return fileNameFilter;
} }

write

 package com.example.alimjan.hello_world;

 /**
* Created by alimjan on 7/5/2017.
*/ import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener; import com.example.alimjan.hello_world.Utils.DateUtil;
import com.example.alimjan.hello_world.Utils.FileUtil; public class class_4_3_2 extends AppCompatActivity implements OnClickListener { private EditText et_name;
private EditText et_age;
private EditText et_height;
private EditText et_weight;
private boolean bMarried = false; private String mPath;
private TextView tv_path; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.code_4_3_2);
et_name = (EditText) findViewById(R.id.et_name);
et_age = (EditText) findViewById(R.id.et_age);
et_height = (EditText) findViewById(R.id.et_height);
et_weight = (EditText) findViewById(R.id.et_weight);
tv_path = (TextView) findViewById(R.id.tv_path);
findViewById(R.id.btn_save).setOnClickListener(this); ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
R.layout.item_select, typeArray);
typeAdapter.setDropDownViewResource(R.layout.item_dropdown);
Spinner sp_married = (Spinner) findViewById(R.id.sp_married);
sp_married.setPrompt("请选择婚姻状况");
sp_married.setAdapter(typeAdapter);
sp_married.setSelection(0);
sp_married.setOnItemSelectedListener(new TypeSelectedListener()); mPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
} private String[] typeArray = {"未婚", "已婚"};
class TypeSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
bMarried = (arg2==0)?false:true;
} public void onNothingSelected(AdapterView<?> arg0) {
}
} @Override
public void onClick(View v) {
if (v.getId() == R.id.btn_save) {
String name = et_name.getText().toString();
String age = et_age.getText().toString();
String height = et_height.getText().toString();
String weight = et_weight.getText().toString();
if (name==null || name.length()<=0) {
showToast("请先填写姓名");
return;
}
if (age==null || age.length()<=0) {
showToast("请先填写年龄");
return;
}
if (height==null || height.length()<=0) {
showToast("请先填写身高");
return;
}
if (weight==null || weight.length()<=0) {
showToast("请先填写体重");
return;
} String content = "";
content = String.format("%s 姓名:%s\n", content, name);
content = String.format("%s 年龄:%s\n", content, age);
content = String.format("%s 身高:%scm\n", content, height);
content = String.format("%s 体重:%skg\n", content, weight);
content = String.format("%s 婚否:%s\n", content, typeArray[bMarried==false?0:1]);
content = String.format("%s 注册时间:%s\n", content, DateUtil.getCurDateStr("yyyy-MM-dd HH:mm:ss"));
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == true) {
String file_path = mPath + DateUtil.getCurDateStr("") + ".txt";
FileUtil.saveText(file_path, content);
tv_path.setText("用户注册信息文件的保存路径为:\n"+file_path);
showToast("数据已写入SD卡文件");
} else {
showToast("未发现已挂载的SD卡,请检查");
}
}
} private void showToast(String desc) {
Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
} public static void startHome(Context mcontext){
Intent intent = new Intent(mcontext,class_4_3_2.class);
mcontext.startActivity(intent);
} }
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:padding="10dp" > <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="姓名:"
android:textColor="@color/black"
android:textSize="17sp" /> <EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/tv_name"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入姓名"
android:inputType="text"
android:maxLength="12"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textCursorDrawable="@drawable/text_cursor"
android:textSize="17sp" />
</RelativeLayout> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_age"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="年龄:"
android:textColor="@color/black"
android:textSize="17sp" /> <EditText
android:id="@+id/et_age"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/tv_age"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入年龄"
android:inputType="number"
android:maxLength="2"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textCursorDrawable="@drawable/text_cursor"
android:textSize="17sp" />
</RelativeLayout> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_height"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="身高:"
android:textColor="@color/black"
android:textSize="17sp" /> <EditText
android:id="@+id/et_height"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/tv_height"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入身高"
android:inputType="number"
android:maxLength="3"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textCursorDrawable="@drawable/text_cursor"
android:textSize="17sp" />
</RelativeLayout> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_weight"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="体重:"
android:textColor="@color/black"
android:textSize="17sp" /> <EditText
android:id="@+id/et_weight"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/tv_weight"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入体重"
android:inputType="numberDecimal"
android:maxLength="5"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textCursorDrawable="@drawable/text_cursor"
android:textSize="17sp" />
</RelativeLayout> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_married"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="婚否:"
android:textColor="@color/black"
android:textSize="17sp" /> <Spinner
android:id="@+id/sp_married"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/tv_married"
android:gravity="left|center"
android:spinnerMode="dialog" />
</RelativeLayout> <Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存文本到SD卡"
android:textColor="@color/black"
android:textSize="20sp" /> <TextView
android:id="@+id/tv_path"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="@color/black"
android:textSize="17sp" /> </LinearLayout>

read

 package com.example.alimjan.hello_world;

 import java.io.File;
import java.util.ArrayList; /**
* Created by alimjan on 7/5/2017.
*/ import com.example.alimjan.hello_world.Utils.FileUtil; import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener; public class class_4_3_2_1 extends AppCompatActivity implements OnClickListener { private final static String TAG = "TextReadActivity";
private TextView tv_text;
private Spinner sp_file;
private String mPath; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.code_4_3_2_1);
tv_text = (TextView) findViewById(R.id.tv_text);
sp_file = (Spinner) findViewById(R.id.sp_file);
findViewById(R.id.btn_delete).setOnClickListener(this);
mPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == true) {
refreshSpinner();
} else {
showToast("未发现已挂载的SD卡,请检查");
}
} private void refreshSpinner() {
ArrayList<File> fileAlllist = FileUtil.getFileList(mPath, new String[]{".txt"});
if (fileAlllist.size() > 0) {
fileArray = new String[fileAlllist.size()];
for (int i=0; i<fileAlllist.size(); i++) {
fileArray[i] = fileAlllist.get(i).getName();
}
ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
R.layout.item_select, fileArray);
typeAdapter.setDropDownViewResource(R.layout.item_dropdown);
sp_file.setPrompt("请选择文本文件");
sp_file.setAdapter(typeAdapter);
sp_file.setSelection(0);
sp_file.setOnItemSelectedListener(new FileSelectedListener());
} else {
fileArray = null;
fileArray = new String[1];
fileArray[0] = "";
ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
R.layout.item_select, fileArray);
sp_file.setPrompt(null);
sp_file.setAdapter(typeAdapter);
sp_file.setOnItemSelectedListener(null);
tv_text.setText("");
}
} private String[] fileArray;
class FileSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String file_path = mPath + fileArray[arg2];
String content = FileUtil.openText(file_path);
tv_text.setText("文件内容如下:\n"+content);
} public void onNothingSelected(AdapterView<?> arg0) {
}
} @Override
public void onClick(View v) {
if (v.getId() == R.id.btn_delete) {
for (int i=0; i<fileArray.length; i++) {
String file_path = mPath + fileArray[i];
File f = new File(file_path);
boolean result = f.delete();
if (result != true) {
Log.d(TAG, "file_path="+file_path+", delete failed");
}
}
refreshSpinner();
showToast("已删除临时目录下的所有文本文件");
}
} private void showToast(String desc) {
Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
} public static void startHome(Context mcontext){
Intent intent = new Intent(mcontext,class_4_3_2_1.class);
mcontext.startActivity(intent);
} }
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:padding="10dp" > <Button
android:id="@+id/btn_delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="删除所有文本文件"
android:textColor="@color/black"
android:textSize="20sp" /> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_file"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="文件名:"
android:textColor="@color/black"
android:textSize="17sp" /> <Spinner
android:id="@+id/sp_file"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/tv_file"
android:gravity="left|center"
android:spinnerMode="dialog" />
</RelativeLayout> <TextView
android:id="@+id/tv_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="17sp" /> </LinearLayout>

Android 开发笔记___SD卡文件操作的更多相关文章

  1. Android 开发笔记&lowbar;&lowbar;&lowbar;SD卡基本操作&lowbar;&lowbar;图片读取写入

    package com.example.alimjan.hello_world.Utils; import android.graphics.Bitmap; import android.graphi ...

  2. Android 开发笔记&lowbar;&lowbar;&lowbar;SD卡基本操作

    package com.example.alimjan.hello_world; /** * Created by alimjan on 7/5/2017. */ import android.ann ...

  3. 【转】Android开发笔记(序)写在前面的目录

    原文:http://blog.csdn.net/aqi00/article/details/50012511 知识点分类 一方面写写自己走过的弯路掉进去的坑,避免以后再犯:另一方面希望通过分享自己的经 ...

  4. Android开发笔记(一百三十四)协调布局CoordinatorLayout

    协调布局CoordinatorLayout Android自5.0之后对UI做了较大的提升.一个重大的改进是推出了MaterialDesign库,而该库的基础即为协调布局CoordinatorLayo ...

  5. &lbrack;置顶&rsqb; Android开发笔记&lpar;成长轨迹&rpar;

    分类: 开发学习笔记2013-06-21 09:44 26043人阅读 评论(5) 收藏 Android开发笔记 1.控制台输出:called unimplemented OpenGL ES API ...

  6. Android开发笔记:打包数据库

    对于数据比较多的控制一般会加入SQLite数据库进行数据存储,在打包时这些数据库是不自动打包到apk中的,如何创建数据库呢 方法1:将创建数据库的sql语句在SQLiteHelper继承类中实现,在第 ...

  7. 【转】Android开发笔记——圆角和边框们

    原文地址:http://blog.xianqu.org/2012/04/android-borders-and-radius-corners/ Android开发笔记——圆角和边框们 在做Androi ...

  8. 《ArcGIS Runtime SDK for Android开发笔记》——离在线一体化技术:概述

    1.前言 数据生产和数据展示是常见的两大专业级移动GIS应用场景,这里我们针对数据生产环节的ArcGIS的离在线一体化技术给大家做一个基本的介绍和梳理. 使用ArcGIS离在线一体化技术首先需要以下基 ...

  9. 《ArcGIS Runtime SDK for Android开发笔记》——离在线一体化技术:离线矢量数据同步

    1.前言 上一篇文章中我们实现了离线要素的编辑操作,这一篇中主要介绍离在线一体化技术中最后一个环节离线数据的同步功能,通过对数据的上传,服务器端的版本化管理,实现数据生产管理的整个流程. 转载请注明出 ...

随机推荐

  1. jQuery method and examples

    一:介绍: jQuery:是DOM和js的封装.jQuery是一个兼容多浏览器的javascript库,核心理念是write less,do more(写得更少,做得更多).现在大多数的pc端的网站都 ...

  2. Android 服务端开发之开发环境配置

    Android 服务端开发之开发环境配置 这里是在Eclipse的基础上安装PhpEclipse插件方法,PHPEclipse是Eclipse的 一个用于开发PHP的插件.当然也可以采用Java开发a ...

  3. PHP 文件操作函数大全

    <?php 读取文件夹: $handler = opendir("c:\");//打开文件夹 while($dir = readdir($handler)){//遍历文件夹 ...

  4. python strip&lpar;&rpar;函数介绍

    函数原型 声明:str为字符串,s为要删除的字符序列 str.strip(s)        删除str字符串中开头.结尾处,位于 s删除序列的字符 str.lstrip(s)       删除str ...

  5. android的animator

    3.0 以前,android支持两种动画模式,tween animation,frame animation,在android3.0中又引入了一个新的动画系统:property animation,这 ...

  6. STM32F4xx时钟理解

    理解力STM32时钟是我们的应用定时器等的基础,据总结近期工作: 以下是一STM32时钟树: 1.首先注意的的是图中画绿色圈圈的两个,HSE和HSI分别表示外部时钟和内部时钟,当中HSE 是是快速外部 ...

  7. FJUT寒假第一周作业浮点数查寻题解

    二分强化——浮点数序列查询 TimeLimit:4000MS  MemoryLimit:128MB 64-bit integer IO format:%I64d Problem Description ...

  8. IE8 disable 兼容行问题

    在chrome 下 如果样式设置为disabled 则不能点击, 但是在IE9 或者IE8 则还是可以点击

  9. C&num; Enum 获取枚举属性

    Enum使用 获取枚举属性 注意:扩展方法必须定义为静态类,静态方法中. public enum EnumPatientSource { [Description("住院")] I ...

  10. HttpServletResponse常见应用——设置响应头控制浏览器的行为

    1.设置http响应头控制浏览器禁止缓存当前文档内容 1 response.setDateHeader("expries", -1); 2 response.setHeader(& ...