【Android学习】Android数据的四种储存方式(2)--File

File:即常说的文件(I/O)储存方式,常用储存大量的数据,但缺点就是更新数据将是一件困难的事情。

下面的程序简单示范了如何读写应用数据文件夹中的文件。该程序的界面同样简单,只包含了两个文本输入框和两个按钮:其中第一组文本框和按钮用于处理输入;第二组文本框用于数据处理。其具体代码如下:

package com.ye_yun_lin.filetest;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;

import javax.security.auth.PrivateCredentialPermission;

import android.os.Bundle;
import android.R.integer;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	final String FILE_NAME = "MyData";
	private EditText editText1;
	private EditText editText2;
	private Button button1;
	private Button button2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		editText1=(EditText)findViewById(R.id.edittext1);
		button1=(Button)findViewById(R.id.button1);
		editText2=(EditText)findViewById(R.id.edittext2);
		button2=(Button)findViewById(R.id.button2);
		
		button1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				write(editText1.getText().toString());
				editText1.setText("");
			}
		});
		
		button2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				editText2.setText(read());
			}
		});
	}
	
	private String read(){
		try {
			FileInputStream fileInputStream=openFileInput(FILE_NAME);
			byte[] buff=new byte[1024];
			int hasRead=0;
			StringBuilder sBuilder=new StringBuilder("");
			while ((hasRead=fileInputStream.read(buff))>0) {
				sBuilder.append(new String(buff,0,hasRead));
			}
			fileInputStream.close();
			return sBuilder.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private void write(String content){
		try {
			FileOutputStream fileOutputStream=openFileOutput(FILE_NAME, MODE_APPEND);
			PrintStream printStream=new PrintStream(fileOutputStream);
			printStream.println(content);
			printStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}



实例:SD卡文件浏览器:

当程序启动时,系统获取/mnt/sdcard目录下的全部文件、文件夹,并使用ListView将他们显示出来;当用户单击ListView的指定列表时,系统将会显示该列表下全部文件夹和文件。

该程序的界面布局文件如下:

<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">

    <TextView
        android:id="@+id/path"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"/>
    <ListView 
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="#000"
        android:dividerHeight="1px"
        android:layout_below="@id/path">
    </ListView>
    <Button 
        android:id="@+id/parent"
        android:layout_width="38dp"
        android:layout_height="34dp"
        android:background="@drawable/home"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

主代码:

package com.ye_yun_lin.sdcard;

import java.io.File;
import java.io.FileOutputStream;
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.R.integer;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private TextView textView;
	private ListView listView;
	private Button button;
	private File currentParent;
	private File[] currentFiles;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		textView=(TextView)findViewById(R.id.path);
		listView=(ListView)findViewById(R.id.list);
		button=(Button)findViewById(R.id.parent);
		
		File root=new File("/mnt/sdcard/");
		if(root.exists()){
			currentParent=root;
			currentFiles=root.listFiles();
			inflateListView(currentFiles);
		}
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				if(currentFiles[position].isFile())
					return;
				File[] tmp=currentFiles[position].listFiles();
				if(tmp==null || tmp.length==0){
					Toast.makeText(MainActivity.this, "当前路径不可访问或该路径下没有文件", Toast.LENGTH_SHORT);
				}
				else{
					currentParent=currentFiles[position];
					currentFiles=tmp;
					inflateListView(currentFiles);
				}
			}
			
		});
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					if (!currentParent.getCanonicalPath().equals("/mnt/sdcard")) {
						currentParent=currentParent.getParentFile();
						currentFiles=currentParent.listFiles();
						inflateListView(currentFiles);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
	private void inflateListView(File[] files){
		List<Map<String,Object>> listItemsListView=new ArrayList<Map<String, Object>>();
		for(int i=0;i<files.length;i++){
			Map<String, Object> listItemMap=new HashMap<String, Object>();
			if(files[i].isDirectory()){
				listItemMap.put("icon", R.drawable.folder);
			}else{
				listItemMap.put("icon", R.drawable.file);
			}
			listItemMap.put("fileName", files[i].getName());
			listItemsListView.add(listItemMap);
		}
		SimpleAdapter simpleAdapter=new SimpleAdapter(this,listItemsListView,R.layout.line,new String[]{"icon","fileName"},new int[]{R.id.icon,R.id.file_name});
		listView.setAdapter(simpleAdapter);
		try {
			textView.setText("当前路径为:"+currentParent.getCanonicalPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


【Android学习】Android数据的四种储存方式(2)--File,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。