首页 > 代码库 > 安卓学习-数据存储与IO-File存储
安卓学习-数据存储与IO-File存储
1.data目录下
MainActivity.java
public class MainActivity extends Activity implements OnClickListener { EditText editText1; TextView textView3; SharedPreferences pre; Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText1 = (EditText) findViewById(R.id.editText1); textView3 = (TextView) findViewById(R.id.textView3); Button btn1 = (Button) findViewById(R.id.button1); Button btn2 = (Button) findViewById(R.id.button2); btn1.setOnClickListener(this); btn2.setOnClickListener(this); } public void onClick(View v) { try { if (v == findViewById(R.id.button1)) { String str=editText1.getText().toString(); FileOutputStream out = openFileOutput("test.bin",Context.MODE_PRIVATE); out.write(str.getBytes()); out.close(); } else if (v == findViewById(R.id.button2)) { FileInputStream in=openFileInput("test.bin"); int len=in.available(); byte[] bytes=new byte[len]; in.read(bytes); in.close(); textView3.setText(new String(bytes)); } } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } }}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText1" android:layout_alignBottom="@+id/editText1" android:layout_alignParentLeft="true" android:text="姓名" android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:layout_toRightOf="@+id/textView1" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/editText1" android:layout_marginTop="22dp" android:text="写入" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/button1" android:layout_marginTop="36dp" android:text="读取" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button2" android:layout_alignBottom="@+id/button2" android:layout_marginLeft="11dp" android:layout_toRightOf="@+id/button2" android:text="值:" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView2" android:layout_alignBottom="@+id/textView2" android:layout_centerHorizontal="true" android:textAppearance="?android:attr/textAppearanceLarge" /></RelativeLayout>
2.SD卡目录下
界面和上面一样
添加权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORA"/>
MainActivity.java
public class MainActivity extends Activity implements OnClickListener { EditText editText1; TextView textView3; SharedPreferences pre; Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText1 = (EditText) findViewById(R.id.editText1); textView3 = (TextView) findViewById(R.id.textView3); Button btn1 = (Button) findViewById(R.id.button1); Button btn2 = (Button) findViewById(R.id.button2); btn1.setOnClickListener(this); btn2.setOnClickListener(this); } public void onClick(View v) { try { if (v == findViewById(R.id.button1)) { //判断是否安装了SD卡 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //获取SD卡路径 /storage/emulated/0 File sdCardDir=Environment.getExternalStorageDirectory(); File file=new File(sdCardDir.getCanonicalPath()+"/test.txt"); //判断文件是否存在,不存在则创建 if(!file.exists()){ file.createNewFile(); } String str=editText1.getText().toString(); //构建out写入数据 FileOutputStream out =new FileOutputStream(file); out.write(str.getBytes()); out.close(); }else{ Toast.makeText(MainActivity.this, "没有发现SD卡", Toast.LENGTH_SHORT).show(); } } else if (v == findViewById(R.id.button2)) { FileInputStream in=new FileInputStream(Environment.getExternalStorageDirectory().getCanonicalPath()+"/test.txt"); int len=in.available(); byte[] bytes=new byte[len]; in.read(bytes); in.close(); textView3.setText(new String(bytes)); } } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } }}
3.获取SD卡目录小程序
点击文件加后,进入下一层目录,点击“父目录”返回上一层
MainActivity.java
public class MainActivity extends Activity { //当前位置路径 String cutFile; TextView textView2; ListView lv; SimpleAdapter adapter; ArrayList<HashMap<String,Object>> fileList=new ArrayList<HashMap<String,Object>>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView2=(TextView)findViewById(R.id.textView2); try { //获取SD卡路径,并保存下来 cutFile=Environment.getExternalStorageDirectory().getCanonicalPath(); textView2.setText(cutFile); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } listFile(cutFile); adapter=new SimpleAdapter(MainActivity.this, fileList, R.layout.item, new String[]{"name","date","icon"}, new int[]{R.id.textView1,R.id.textView2,R.id.imageView1}); lv=(ListView)findViewById(R.id.listView1); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt, long paramLong) { //点击时,获取当前点击的项信息 HashMap<String,Object> map=fileList.get(paramInt); String name=map.get("name")+""; String path=map.get("path")+""; File file=new File(path); //判断是否是目录 if(file.isDirectory()){ //是否是回到上一层 if(name.equals("..")){ //获取上一层目录 File file11=new File(path); listFile(file11.getParentFile().getPath()); }else{ listFile(path); } //刷新 adapter.notifyDataSetChanged(); } } }); } public void listFile(String path){ cutFile=path; textView2.setText(cutFile); //清空 fileList.clear(); //第一层目录,不添加父目录项 try { if(!path.equals(Environment.getExternalStorageDirectory().getCanonicalPath())){ HashMap<String,Object> map1=new HashMap<String,Object>(); map1.put("name", ".."); map1.put("date", "父目录"); map1.put("icon", R.drawable.folder); map1.put("path", cutFile); fileList.add(map1); } } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } File sdCardDir=new File(path); File[] list=sdCardDir.listFiles(); for(int i=0;i<list.length;i++){ File file=list[i]; HashMap<String,Object> map=new HashMap<String,Object>(); //获取文件名 map.put("name", file.getName()); //获取修改时间 Long time =file.lastModified(); Calendar cd = Calendar.getInstance(); cd.setTimeInMillis(time); Date tasktime=cd.getTime(); //设置日期输出的格式 SimpleDateFormat df=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); //格式化输出 map.put("date", df.format(tasktime)); //判断是否是目录 if(file.isDirectory()){ map.put("icon", R.drawable.folder); }else{ map.put("icon", R.drawable.invoice); } map.put("path",cutFile+"/"+file.getName()); fileList.add(map); } } }
item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_alignParentRight="true" android:layout_below="@+id/textView1" android:text="创建时间" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/imageView1" android:layout_marginLeft="15dp" android:layout_toRightOf="@+id/imageView1" android:text="文件名" android:textAppearance="?android:attr/textAppearanceSmall" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="19dp" android:src="@drawable/folder" /></RelativeLayout>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" > </ListView> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="当前路径:" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="14dp" android:layout_toRightOf="@+id/textView1" android:text="当前路径" android:textAppearance="?android:attr/textAppearanceSmall" /></RelativeLayout>
两个图片资源
folder.png
invoice.png
安卓学习-数据存储与IO-File存储
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。