Android 开发笔记___SD卡文件操作

  1 package com.example.alimjan.hello_world.Utils;
  2 
  3 import android.graphics.Bitmap;
  4 import android.graphics.BitmapFactory;
  5 
  6 import java.io.BufferedInputStream;
  7 import java.io.BufferedOutputStream;
  8 import java.io.File;
  9 import java.io.FileInputStream;
 10 import java.io.FileOutputStream;
 11 import java.io.FilenameFilter;
 12 import java.util.ArrayList;
 13 import java.util.Locale;
 14 
 15 public class FileUtil {
 16 
 17     public static void saveText(String path, String txt) {
 18         try {
 19             FileOutputStream fos = new FileOutputStream(path);
 20             fos.write(txt.getBytes());
 21             fos.close();
 22         } catch (Exception e) {
 23             e.printStackTrace();
 24         }
 25     }
 26 
 27     public static String openText(String path) {
 28         String readStr = "";
 29         try {
 30             FileInputStream fis = new FileInputStream(path);
 31             byte[] b = new byte[fis.available()];
 32             fis.read(b);
 33             readStr = new String(b);
 34             fis.close();
 35         } catch (Exception e) {
 36             e.printStackTrace();
 37         }
 38         return readStr;
 39     }
 40 
 41     public static void saveImage(String path, Bitmap bitmap) {
 42         try {
 43             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
 44             bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
 45             bos.flush();
 46             bos.close();
 47         } catch (Exception e) {
 48             e.printStackTrace();
 49         }
 50     }
 51     
 52     public static Bitmap openImage(String path) {
 53         Bitmap bitmap = null;
 54         try {
 55             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
 56             bitmap = BitmapFactory.decodeStream(bis);
 57             bis.close();
 58         } catch (Exception e) {
 59             e.printStackTrace();
 60         }
 61         return bitmap;
 62     }
 63     
 64     public static ArrayList<File> getFileList(String path, String[] extendArray) {
 65         ArrayList<File> displayedContent = new ArrayList<File>();
 66         File[] files = null;
 67         File directory = new File(path);
 68         if (extendArray != null && extendArray.length>0) {
 69             FilenameFilter fileFilter = getTypeFilter(extendArray);
 70             files = directory.listFiles(fileFilter);
 71         } else {
 72             files = directory.listFiles();
 73         }
 74 
 75         if (files != null) {
 76             for (File f : files) {
 77                 if (!f.isDirectory() && !f.isHidden()) {
 78                     displayedContent.add(f);
 79                 }
 80             }
 81         }
 82         return displayedContent;
 83     }
 84 
 85     public static FilenameFilter getTypeFilter(String[] extendArray) {
 86         final ArrayList<String> fileExtensions = new ArrayList<String>();
 87         for (int i=0; i<extendArray.length; i++) {
 88             fileExtensions.add(extendArray[i]);
 89         }
 90         FilenameFilter fileNameFilter = new FilenameFilter() {
 91             @Override
 92             public boolean accept(File directory, String fileName) {
 93                 boolean matched = false;
 94                 File f = new File(String.format("%s/%s",
 95                         directory.getAbsolutePath(), fileName));
 96                 matched = f.isDirectory();
 97                 if (!matched) {
 98                     for (String s : fileExtensions) {
 99                         s = String.format(".{0,}\\%s$", s);
100                         s = s.toUpperCase(Locale.getDefault());
101                         fileName = fileName.toUpperCase(Locale.getDefault());
102                         matched = fileName.matches(s);
103                         if (matched) {
104                             break;
105                         }
106                     }
107                 }
108                 return matched;
109             }
110         };
111         return fileNameFilter;
112     }
113 
114 }

write

  1 package com.example.alimjan.hello_world;
  2 
  3 /**
  4  * Created by alimjan on 7/5/2017.
  5  */
  6 
  7 
  8         import android.content.Context;
  9         import android.content.Intent;
 10         import android.os.Bundle;
 11         import android.os.Environment;
 12         import android.support.v7.app.AppCompatActivity;
 13         import android.view.View;
 14         import android.view.View.OnClickListener;
 15         import android.widget.AdapterView;
 16         import android.widget.ArrayAdapter;
 17         import android.widget.EditText;
 18         import android.widget.Spinner;
 19         import android.widget.TextView;
 20         import android.widget.Toast;
 21         import android.widget.AdapterView.OnItemSelectedListener;
 22 
 23         import com.example.alimjan.hello_world.Utils.DateUtil;
 24         import com.example.alimjan.hello_world.Utils.FileUtil;
 25 
 26 
 27 public class class_4_3_2 extends AppCompatActivity implements OnClickListener {
 28 
 29     private EditText et_name;
 30     private EditText et_age;
 31     private EditText et_height;
 32     private EditText et_weight;
 33     private boolean bMarried = false;
 34 
 35     private String mPath;
 36     private TextView tv_path;
 37 
 38     @Override
 39     protected void onCreate(Bundle savedInstanceState) {
 40         super.onCreate(savedInstanceState);
 41         setContentView(R.layout.code_4_3_2);
 42         et_name = (EditText) findViewById(R.id.et_name);
 43         et_age = (EditText) findViewById(R.id.et_age);
 44         et_height = (EditText) findViewById(R.id.et_height);
 45         et_weight = (EditText) findViewById(R.id.et_weight);
 46         tv_path = (TextView) findViewById(R.id.tv_path);
 47         findViewById(R.id.btn_save).setOnClickListener(this);
 48 
 49         ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
 50                 R.layout.item_select, typeArray);
 51         typeAdapter.setDropDownViewResource(R.layout.item_dropdown);
 52         Spinner sp_married = (Spinner) findViewById(R.id.sp_married);
 53         sp_married.setPrompt("请选择婚姻状况");
 54         sp_married.setAdapter(typeAdapter);
 55         sp_married.setSelection(0);
 56         sp_married.setOnItemSelectedListener(new TypeSelectedListener());
 57 
 58         mPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
 59     }
 60 
 61     private String[] typeArray = {"未婚", "已婚"};
 62     class TypeSelectedListener implements OnItemSelectedListener {
 63         public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
 64             bMarried = (arg2==0)?false:true;
 65         }
 66 
 67         public void onNothingSelected(AdapterView<?> arg0) {
 68         }
 69     }
 70 
 71     @Override
 72     public void onClick(View v) {
 73         if (v.getId() == R.id.btn_save) {
 74             String name = et_name.getText().toString();
 75             String age = et_age.getText().toString();
 76             String height = et_height.getText().toString();
 77             String weight = et_weight.getText().toString();
 78             if (name==null || name.length()<=0) {
 79                 showToast("请先填写姓名");
 80                 return;
 81             }
 82             if (age==null || age.length()<=0) {
 83                 showToast("请先填写年龄");
 84                 return;
 85             }
 86             if (height==null || height.length()<=0) {
 87                 showToast("请先填写身高");
 88                 return;
 89             }
 90             if (weight==null || weight.length()<=0) {
 91                 showToast("请先填写体重");
 92                 return;
 93             }
 94 
 95             String content = "";
 96             content = String.format("%s 姓名:%s\n", content, name);
 97             content = String.format("%s 年龄:%s\n", content, age);
 98             content = String.format("%s 身高:%scm\n", content, height);
 99             content = String.format("%s 体重:%skg\n", content, weight);
100             content = String.format("%s 婚否:%s\n", content, typeArray[bMarried==false?0:1]);
101             content = String.format("%s 注册时间:%s\n", content, DateUtil.getCurDateStr("yyyy-MM-dd HH:mm:ss"));
102             if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == true) {
103                 String file_path = mPath + DateUtil.getCurDateStr("") + ".txt";
104                 FileUtil.saveText(file_path, content);
105                 tv_path.setText("用户注册信息文件的保存路径为:\n"+file_path);
106                 showToast("数据已写入SD卡文件");
107             } else {
108                 showToast("未发现已挂载的SD卡,请检查");
109             }
110         }
111     }
112 
113     private void showToast(String desc) {
114         Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
115     }
116 
117     public static void startHome(Context mcontext){
118         Intent intent = new Intent(mcontext,class_4_3_2.class);
119         mcontext.startActivity(intent);
120     }
121 
122 }
  1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2     android:layout_width="match_parent"
  3     android:layout_height="match_parent"
  4     android:focusable="true"
  5     android:focusableInTouchMode="true"
  6     android:orientation="vertical"
  7     android:padding="10dp" >
  8 
  9     <RelativeLayout
 10         android:layout_width="match_parent"
 11         android:layout_height="50dp" >
 12 
 13         <TextView
 14             android:id="@+id/tv_name"
 15             android:layout_width="wrap_content"
 16             android:layout_height="match_parent"
 17             android:layout_alignParentLeft="true"
 18             android:gravity="center"
 19             android:text="姓名:"
 20             android:textColor="@color/black"
 21             android:textSize="17sp" />
 22 
 23         <EditText
 24             android:id="@+id/et_name"
 25             android:layout_width="match_parent"
 26             android:layout_height="match_parent"
 27             android:layout_marginBottom="5dp"
 28             android:layout_marginTop="5dp"
 29             android:layout_toRightOf="@+id/tv_name"
 30             android:background="@drawable/editext_selector"
 31             android:gravity="left|center"
 32             android:hint="请输入姓名"
 33             android:inputType="text"
 34             android:maxLength="12"
 35             android:textColor="@color/black"
 36             android:textColorHint="@color/grey"
 37             android:textCursorDrawable="@drawable/text_cursor"
 38             android:textSize="17sp" />
 39     </RelativeLayout>
 40 
 41     <RelativeLayout
 42         android:layout_width="match_parent"
 43         android:layout_height="50dp" >
 44 
 45         <TextView
 46             android:id="@+id/tv_age"
 47             android:layout_width="wrap_content"
 48             android:layout_height="match_parent"
 49             android:layout_alignParentLeft="true"
 50             android:gravity="center"
 51             android:text="年龄:"
 52             android:textColor="@color/black"
 53             android:textSize="17sp" />
 54 
 55         <EditText
 56             android:id="@+id/et_age"
 57             android:layout_width="match_parent"
 58             android:layout_height="match_parent"
 59             android:layout_marginBottom="5dp"
 60             android:layout_marginTop="5dp"
 61             android:layout_toRightOf="@+id/tv_age"
 62             android:background="@drawable/editext_selector"
 63             android:gravity="left|center"
 64             android:hint="请输入年龄"
 65             android:inputType="number"
 66             android:maxLength="2"
 67             android:textColor="@color/black"
 68             android:textColorHint="@color/grey"
 69             android:textCursorDrawable="@drawable/text_cursor"
 70             android:textSize="17sp" />
 71     </RelativeLayout>
 72 
 73     <RelativeLayout
 74         android:layout_width="match_parent"
 75         android:layout_height="50dp" >
 76 
 77         <TextView
 78             android:id="@+id/tv_height"
 79             android:layout_width="wrap_content"
 80             android:layout_height="match_parent"
 81             android:layout_alignParentLeft="true"
 82             android:gravity="center"
 83             android:text="身高:"
 84             android:textColor="@color/black"
 85             android:textSize="17sp" />
 86 
 87         <EditText
 88             android:id="@+id/et_height"
 89             android:layout_width="match_parent"
 90             android:layout_height="match_parent"
 91             android:layout_marginBottom="5dp"
 92             android:layout_marginTop="5dp"
 93             android:layout_toRightOf="@+id/tv_height"
 94             android:background="@drawable/editext_selector"
 95             android:gravity="left|center"
 96             android:hint="请输入身高"
 97             android:inputType="number"
 98             android:maxLength="3"
 99             android:textColor="@color/black"
100             android:textColorHint="@color/grey"
101             android:textCursorDrawable="@drawable/text_cursor"
102             android:textSize="17sp" />
103     </RelativeLayout>
104 
105     <RelativeLayout
106         android:layout_width="match_parent"
107         android:layout_height="50dp" >
108 
109         <TextView
110             android:id="@+id/tv_weight"
111             android:layout_width="wrap_content"
112             android:layout_height="match_parent"
113             android:layout_alignParentLeft="true"
114             android:gravity="center"
115             android:text="体重:"
116             android:textColor="@color/black"
117             android:textSize="17sp" />
118 
119         <EditText
120             android:id="@+id/et_weight"
121             android:layout_width="match_parent"
122             android:layout_height="match_parent"
123             android:layout_marginBottom="5dp"
124             android:layout_marginTop="5dp"
125             android:layout_toRightOf="@+id/tv_weight"
126             android:background="@drawable/editext_selector"
127             android:gravity="left|center"
128             android:hint="请输入体重"
129             android:inputType="numberDecimal"
130             android:maxLength="5"
131             android:textColor="@color/black"
132             android:textColorHint="@color/grey"
133             android:textCursorDrawable="@drawable/text_cursor"
134             android:textSize="17sp" />
135     </RelativeLayout>
136 
137     <RelativeLayout
138         android:layout_width="match_parent"
139         android:layout_height="50dp" >
140 
141         <TextView
142             android:id="@+id/tv_married"
143             android:layout_width="wrap_content"
144             android:layout_height="match_parent"
145             android:layout_alignParentLeft="true"
146             android:gravity="center"
147             android:text="婚否:"
148             android:textColor="@color/black"
149             android:textSize="17sp" />
150 
151         <Spinner
152             android:id="@+id/sp_married"
153             android:layout_width="match_parent"
154             android:layout_height="match_parent"
155             android:layout_toRightOf="@+id/tv_married"
156             android:gravity="left|center"
157             android:spinnerMode="dialog" />
158     </RelativeLayout>
159 
160     <Button
161         android:id="@+id/btn_save"
162         android:layout_width="match_parent"
163         android:layout_height="wrap_content"
164         android:text="保存文本到SD卡"
165         android:textColor="@color/black"
166         android:textSize="20sp" />
167 
168     <TextView
169         android:id="@+id/tv_path"
170         android:layout_width="wrap_content"
171         android:layout_height="match_parent"
172         android:textColor="@color/black"
173         android:textSize="17sp" />
174 
175 </LinearLayout>

read

  1 package com.example.alimjan.hello_world;
  2 
  3 import java.io.File;
  4 import java.util.ArrayList;
  5 
  6 /**
  7  * Created by alimjan on 7/5/2017.
  8  */
  9 
 10 
 11         import com.example.alimjan.hello_world.Utils.FileUtil;
 12 
 13 import android.content.Context;
 14 import android.content.Intent;
 15 import android.os.Bundle;
 16         import android.os.Environment;
 17         import android.support.v7.app.AppCompatActivity;
 18         import android.util.Log;
 19         import android.view.View;
 20         import android.view.View.OnClickListener;
 21         import android.widget.AdapterView;
 22         import android.widget.ArrayAdapter;
 23         import android.widget.Spinner;
 24         import android.widget.TextView;
 25         import android.widget.Toast;
 26         import android.widget.AdapterView.OnItemSelectedListener;
 27 
 28 public class class_4_3_2_1 extends AppCompatActivity implements OnClickListener {
 29 
 30     private final static String TAG = "TextReadActivity";
 31     private TextView tv_text;
 32     private Spinner sp_file;
 33     private String mPath;
 34 
 35     @Override
 36     protected void onCreate(Bundle savedInstanceState) {
 37         super.onCreate(savedInstanceState);
 38         setContentView(R.layout.code_4_3_2_1);
 39         tv_text = (TextView) findViewById(R.id.tv_text);
 40         sp_file = (Spinner) findViewById(R.id.sp_file);
 41         findViewById(R.id.btn_delete).setOnClickListener(this);
 42         mPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
 43         if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == true) {
 44             refreshSpinner();
 45         } else {
 46             showToast("未发现已挂载的SD卡,请检查");
 47         }
 48     }
 49 
 50     private void refreshSpinner() {
 51         ArrayList<File> fileAlllist = FileUtil.getFileList(mPath, new String[]{".txt"});
 52         if (fileAlllist.size() > 0) {
 53             fileArray = new String[fileAlllist.size()];
 54             for (int i=0; i<fileAlllist.size(); i++) {
 55                 fileArray[i] = fileAlllist.get(i).getName();
 56             }
 57             ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
 58                     R.layout.item_select, fileArray);
 59             typeAdapter.setDropDownViewResource(R.layout.item_dropdown);
 60             sp_file.setPrompt("请选择文本文件");
 61             sp_file.setAdapter(typeAdapter);
 62             sp_file.setSelection(0);
 63             sp_file.setOnItemSelectedListener(new FileSelectedListener());
 64         } else {
 65             fileArray = null;
 66             fileArray = new String[1];
 67             fileArray[0] = "";
 68             ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
 69                     R.layout.item_select, fileArray);
 70             sp_file.setPrompt(null);
 71             sp_file.setAdapter(typeAdapter);
 72             sp_file.setOnItemSelectedListener(null);
 73             tv_text.setText("");
 74         }
 75     }
 76 
 77     private String[] fileArray;
 78     class FileSelectedListener implements OnItemSelectedListener {
 79         public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
 80             String file_path = mPath + fileArray[arg2];
 81             String content = FileUtil.openText(file_path);
 82             tv_text.setText("文件内容如下:\n"+content);
 83         }
 84 
 85         public void onNothingSelected(AdapterView<?> arg0) {
 86         }
 87     }
 88 
 89     @Override
 90     public void onClick(View v) {
 91         if (v.getId() == R.id.btn_delete) {
 92             for (int i=0; i<fileArray.length; i++) {
 93                 String file_path = mPath + fileArray[i];
 94                 File f = new File(file_path);
 95                 boolean result = f.delete();
 96                 if (result != true) {
 97                     Log.d(TAG, "file_path="+file_path+", delete failed");
 98                 }
 99             }
100             refreshSpinner();
101             showToast("已删除临时目录下的所有文本文件");
102         }
103     }
104 
105     private void showToast(String desc) {
106         Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
107     }
108 
109     public static void startHome(Context mcontext){
110         Intent intent = new Intent(mcontext,class_4_3_2_1.class);
111         mcontext.startActivity(intent);
112     }
113 
114 }
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:layout_width="match_parent"
 3     android:layout_height="match_parent"
 4     android:focusable="true"
 5     android:focusableInTouchMode="true"
 6     android:orientation="vertical"
 7     android:padding="10dp" >
 8 
 9     <Button
10         android:id="@+id/btn_delete"
11         android:layout_width="match_parent"
12         android:layout_height="wrap_content"
13         android:text="删除所有文本文件"
14         android:textColor="@color/black"
15         android:textSize="20sp" />
16 
17     <RelativeLayout
18         android:layout_width="match_parent"
19         android:layout_height="50dp" >
20 
21         <TextView
22             android:id="@+id/tv_file"
23             android:layout_width="wrap_content"
24             android:layout_height="match_parent"
25             android:layout_alignParentLeft="true"
26             android:gravity="center"
27             android:text="文件名:"
28             android:textColor="@color/black"
29             android:textSize="17sp" />
30 
31         <Spinner
32             android:id="@+id/sp_file"
33             android:layout_width="match_parent"
34             android:layout_height="match_parent"
35             android:layout_toRightOf="@+id/tv_file"
36             android:gravity="left|center"
37             android:spinnerMode="dialog" />
38     </RelativeLayout>
39 
40     <TextView
41         android:id="@+id/tv_text"
42         android:layout_width="match_parent"
43         android:layout_height="wrap_content"
44         android:textColor="@color/black"
45         android:textSize="17sp" />
46 
47 </LinearLayout>

 

posted @ 2017-07-05 12:16  alm  阅读(241)  评论(0编辑  收藏  举报