SDCard文件读写与目录浏览 笔记

来源:互联网 发布:sql select null as 编辑:程序博客网 时间:2024/06/12 00:09

1.SD 卡文件的读写  

package com.example.sdcardtest; import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStreamReader;import java.io.PrintStream;import java.io.RandomAccessFile;   import android.os.Bundle;import android.os.Environment;import android.app.Activity;import android.content.Context;import android.view.Menu;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; public class SDCardTest extendsActivity {        //        privateButton read_bt;        privateButton write_bt;        privateTextView show;        privateEditText edit;        finalString filename = "/test/data.txt";        //    @Override    protected void onCreate(BundlesavedInstanceState) {        super.onCreate(savedInstanceState);       setContentView(R.layout.activity_sdcard_test);        //        read_bt =(Button)findViewById(R.id.read_bt);        write_bt =(Button)findViewById(R.id.write_bt);        show =(TextView)findViewById(R.id.show);        edit =(EditText)findViewById(R.id.edit);               read_bt.setOnClickListener(newView.OnClickListener() {                                             @Override                       publicvoid onClick(View arg0) {                               //TODO Auto-generated method stub                               Strings = read();                               if(s== null){                                      Toast.makeText(getApplicationContext(),"text is null",                                                     Toast.LENGTH_LONG).show();                               }                               else{                                      show.setText(s);                                      }                                                                    }               });               write_bt.setOnClickListener(newView.OnClickListener() {                                             @Override                       publicvoid onClick(View v) {                               //TODO Auto-generated method stub                               Strings = edit.getText().toString();//to String (not cast to String)                               write(s);                               edit.setText("");//clearthe EditText                       }               });        //    }     //    private String read(){    /*  try{               //  abstract FileOutputStream  openFileOutput(String name, int mode) //  Open a private file associatedwith this Context's application package for writing.               //打开文件输入流               FileInputStreamfis = openFileInput(filename);               byte[]buf = new byte[1024];               StringBuildersb = new StringBuilder("");               intreadbytes = 0;               //读取文件内容               while((readbytes=fis.read(buf))!=-1){                       sb.append(newString(buf,0,readbytes));//字节转换为字符串               }               //关闭文件流               fis.close();               returnsb.toString();                      }catch(Exceptione){               e.printStackTrace();        }               returnnull;        */                      //readSDCard Data               try{               if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){                       //获取SD卡对应的存储目录                       FilesdCardDir = Environment.getExternalStorageDirectory();                       //获取指定文件对应的输入流                       //getCanonicalPath  返回此抽象路径名的规范路径名字符串。                                                                   FileInputStreamfis = new FileInputStream(sdCardDir.getCanonicalPath()                                      +filename);                       //字节流-->转字符流  并包装-->称BufferdeReder                       BufferedReaderbr = new BufferedReader(new InputStreamReader(fis));                       Stringline = null;                       Strings = "";                       s+= (sdCardDir.getCanonicalPath()+ filename + "\n");                       while((line=br.readLine())!=null){                              s+= line;                       }                       br.close();                       returns;                                     }               }catch(Exceptione){                       e.printStackTrace();                                     }        returnnull;                  }       private void write(String content){        /*        try{               //以追加模式打开文件输入流   Context.MODE_APPEND               FileOutputStreamfos = openFileOutput(filename, Context.MODE_APPEND);               //将FileOutputStream包装成PrintStream               PrintStreamps = new PrintStream(fos);               //synchronizedvoid    println(String str)          //  Prints a string followed by a newline.               ps.println(content);//输出文件内容        }catch(Exceptione){               e.printStackTrace();                      }        */               try{               if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){                       FilesdCardDir = Environment.getExternalStorageDirectory();                                     /*      FileOutputStream fos =openFileOutput(sdCardDir.getCanonicalPath() + filename,                                      Context.MODE_APPEND);                       PrintStreamps = new PrintStream(fos);                       ps.println(content);                       ps.close();*/                                                     FileTargetFile = new File(sdCardDir.getCanonicalPath() + filename);                       //以指定文件创建RandomAccessFile对象                       RandomAccessFileraf = new RandomAccessFile(TargetFile,"rw");                       //将文件记录指针移到最后                       raf.seek(TargetFile.length());                       //输出文件内容    使用RandomAccessFile对象写文件                       raf.write(content.getBytes());//String-->bytes[]                        raf.close();                                     }        }catch(Exceptione){               e.printStackTrace();        }       }}

2.SD卡文件浏览

(1)SDCardBrowser.java

packagecom.example.sdcardbrowser; import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; import android.os.Bundle;import android.os.Environment;import android.app.Activity;import android.view.Menu;import android.view.View;importandroid.widget.AdapterView;import android.widget.Button;import android.widget.ListView;importandroid.widget.SimpleAdapter;import android.widget.TextView;import android.widget.Toast; public class SDCardBrowserextends Activity {        //        ListViewlistview;        TextViewcurrent_path;        FileCurrentParent;        File[]CurrentFiles;        Buttonparent;        //    @Override    protected void onCreate(BundlesavedInstanceState) {        super.onCreate(savedInstanceState);       setContentView(R.layout.activity_sdcard_browser);        //        listview =(ListView)findViewById(R.id.list);        current_path = (TextView)findViewById(R.id.path);        parent =(Button)findViewById(R.id.parent);        init();        //click the list item,enter the filefolder        listview.setOnItemClickListener(newAdapterView.OnItemClickListener() {                        @Override                       publicvoid onItemClick(AdapterView<?> parent, View view,                                      intposition, long id) {// get position                               //TODO Auto-generated method stub                               if(CurrentFiles[position].isFile()){//is file                                      //donothing                               }                               else{//isdirectory                                      File[]temp = CurrentFiles[position].listFiles();                                       if(temp== null ||temp.length == 0){                                              Toast.makeText(SDCardBrowser.this,"no file",                                                             Toast.LENGTH_LONG).show();                                                                                   //      TextView no_file = (TextView)getLayoutInflater().inflate(R.layout.no_filehint, null);                                              //showthis no_file TextView in the center                                                                                           try{//show current path                                                      current_path.setText(CurrentFiles[position].getCanonicalPath());                                              }catch (IOException e) {                                                     //TODO Auto-generated catch block                                                     e.printStackTrace();                                              }                                                                                   }else{//updateCurrentParent and  CurrentFiles                                              CurrentParent= CurrentFiles[position];                                              CurrentFiles= temp;                                              SDCardBrowser.this.inflateListView(CurrentFiles);                                      }                               }                               }               });               //back to parent directory        parent.setOnClickListener(newView.OnClickListener() {                                             @Override                       publicvoid onClick(View v) {                               //TODO Auto-generated method stub                               try{//current parent is not dir /mnt/sdcard0 etc                                      if(!CurrentParent.getCanonicalPath().equals(Environment                                                      .getExternalStorageDirectory().getCanonicalPath())){                                              CurrentParent= CurrentParent.getParentFile();                                              CurrentFiles=CurrentParent.listFiles();                                              SDCardBrowser.this.inflateListView(CurrentFiles);                                      }                               }catch (IOException e) {                                      //TODO Auto-generated catch block                                      e.printStackTrace();                               }                              }               });    }       //initial the program    private void init(){        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){               FileSDCardDir = Environment.getExternalStorageDirectory();                             CurrentParent= SDCardDir;               CurrentFiles= SDCardDir.listFiles();               if(CurrentFiles== null || CurrentFiles.length == 0){                                     }else{                       inflateListView(CurrentFiles);               }        }    }       //inflate the listview with file list    private void inflateListView(File []files){                      List<Map<String,Object>>filelist = new ArrayList<Map<String,Object>>();                      for(inti = 0;i<files.length;i++){               Map<String,Object>listItem = new HashMap<String,Object>();// in the for()  not outside               //icon               if(files[i].isDirectory()){//isfolder                       listItem.put("icon",R.drawable.folder);               }elseif(files[i].isFile()){//if file                       listItem.put("icon",R.drawable.file);               }               //name               listItem.put("filename",files[i].getName());               filelist.add(listItem);        }               SimpleAdapteradapter = new SimpleAdapter(this, filelist, R.layout.line,                       newString[]{"icon","filename"}, newint[]{R.id.icon,R.id.file_name});               listview.setAdapter(adapter);               try{//show current path                       current_path.setText(CurrentParent.getCanonicalPath());               }catch (IOException e) {                       //TODO Auto-generated catch block                       e.printStackTrace();               }    }}

(2)activity_sdcard_browser.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical">    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" ><!-- 显示**当前路径**的文本框 --><TextView  android:id="@+id/path"android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"android:layout_weight="4"/><!-- 返回上一级目录的按钮 --><Button     android:id="@+id/parent"android:layout_width="0dp" android:layout_height="34dp" android:background="@drawable/home"android:layout_weight="1"/></LinearLayout>       <!-- 列出**当前路径下所有文件**的ListView -->   <ListView  android:id="@+id/list"android:layout_width="wrap_content" android:layout_height="wrap_content" android:divider="#000"android:dividerHeight="1px"/></LinearLayout>

(3)line.xml

<?xml version="1.0" encoding="UTF-8"?><LinearLayoutandroid:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"><!-- 定义一个ImageView,用于作为列表项的一部分。 --><ImageView android:id="@+id/icon"android:layout_width="40dp"android:layout_height="40dp" android:paddingLeft="10dp"/><!-- 定义一个TextView,用于作为列表项的一部分。 --><TextView android:id="@+id/file_name"android:layout_width="wrap_content" android:layout_height="wrap_content"android:textSize="16dp"android:gravity="center_vertical"android:paddingLeft="10dp"android:paddingTop="10dp"android:paddingBottom="10dp"/></LinearLayout>

(4)在AndroidManifest.xml中添加相应的权限

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

 运行结果:


 

 

0 0
原创粉丝点击